List of usage examples for io.netty.handler.ssl SslContextBuilder build
public SslContext build() throws SSLException
From source file:org.conscrypt.testing.TestUtil.java
License:Apache License
public static SslContext newNettyServerContext(String cipher) { try {/* www . j a v a 2 s . c o m*/ PrivateKeyEntry server = TestKeyStore.getServer().getPrivateKey("RSA", "RSA"); SslContextBuilder ctx = SslContextBuilder .forServer(server.getPrivateKey(), (X509Certificate[]) server.getCertificateChain()) .sslProvider(io.netty.handler.ssl.SslProvider.OPENSSL); if (cipher != null) { ctx.ciphers(Collections.singletonList(cipher)); } return ctx.build(); } catch (SSLException e) { throw new RuntimeException(e); } }
From source file:org.curioswitch.common.server.framework.ServerModule.java
License:Open Source License
@SuppressWarnings("FutureReturnValueIgnored") @Provides//from w ww . ja v a 2 s. c o m @Singleton static Server armeriaServer(Set<BindableService> grpcServices, Set<GrpcServiceDefinition> grpcServiceDefinitions, Set<HttpServiceDefinition> httpServiceDefinitions, Set<StaticSiteServiceDefinition> staticSites, Set<Consumer<ServerBuilder>> serverCustomizers, Set<PostServerCustomizer> postServerCustomizers, Set<WatchedPath> watchedPaths, Function<Service<HttpRequest, HttpResponse>, LoggingService<HttpRequest, HttpResponse>> loggingService, MetricsHttpService metricsHttpService, CollectorRegistry collectorRegistry, MeterRegistry meterRegistry, Tracing tracing, Lazy<FirebaseAuthorizer> firebaseAuthorizer, Lazy<JwtAuthorizer.Factory> jwtAuthorizer, Lazy<JavascriptStaticService> javascriptStaticService, Optional<SelfSignedCertificate> selfSignedCertificate, Optional<TrustManagerFactory> caTrustManager, Optional<SslCommonNamesProvider> sslCommonNamesProvider, FileWatcher.Builder fileWatcherBuilder, Lazy<StackdriverReporter> stackdriverReporter, ServerConfig serverConfig, FirebaseAuthConfig authConfig, HttpsOnlyService.Factory httpsOnlyServiceFactory, JavascriptStaticConfig javascriptStaticConfig, MonitoringConfig monitoringConfig, SecurityConfig securityConfig, Set<ServerShutDownDelayer> serverShutDownDelayers, @CloseOnStop Set<Closeable> closeOnStopDependencies, // Eagerly trigger bindings that are present, not actually used here. @EagerInit Set<Object> eagerInitializedDependencies) { for (WatchedPath watched : watchedPaths) { fileWatcherBuilder.registerPath(watched.getPath(), watched.getHandler()); } if (!sslCommonNamesProvider.isPresent() && !serverConfig.getRpcAclsPath().isEmpty() && !serverConfig.isDisableSslAuthorization()) { Path path = Paths.get(serverConfig.getRpcAclsPath()).toAbsolutePath(); RpcAclsCommonNamesProvider commonNamesProvider = new RpcAclsCommonNamesProvider(path); fileWatcherBuilder.registerPath(path, commonNamesProvider::processFile); if (path.toFile().exists()) { commonNamesProvider.processFile(path); } sslCommonNamesProvider = Optional.of(commonNamesProvider); } ServerBuilder sb = new ServerBuilder().https(serverConfig.getPort()); if (selfSignedCertificate.isPresent()) { SelfSignedCertificate certificate = selfSignedCertificate.get(); try { SslContextBuilder sslContext = serverSslContext( ResourceUtil.openStream(certificate.certificate().getAbsolutePath()), ResourceUtil.openStream(certificate.privateKey().getAbsolutePath())) .trustManager(InsecureTrustManagerFactory.INSTANCE); if (!serverConfig.isDisableSslAuthorization()) { sslContext.clientAuth(ClientAuth.OPTIONAL); } sb.tls(sslContext.build()); } catch (SSLException e) { // Can't happen. throw new IllegalStateException(e); } } else if (serverConfig.getTlsCertificatePath().isEmpty() || serverConfig.getTlsPrivateKeyPath().isEmpty() || !caTrustManager.isPresent()) { throw new IllegalStateException( "No TLS configuration provided, Curiostack does not support non-TLS servers. " + "Use gradle-curio-cluster-plugin to set up a namespace and TLS."); } else { try { SslContextBuilder sslContext = serverSslContext( ResourceUtil.openStream(serverConfig.getTlsCertificatePath()), ResourceUtil.openStream(serverConfig.getTlsPrivateKeyPath())) .trustManager(caTrustManager.get()); if (!serverConfig.isDisableSslAuthorization()) { sslContext.clientAuth(ClientAuth.OPTIONAL); } sb.tls(sslContext.build()); } catch (SSLException e) { throw new IllegalStateException("Could not load TLS certificate.", e); } } serverCustomizers.forEach(c -> c.accept(sb)); Optional<Function<Service<HttpRequest, HttpResponse>, IpFilteringService>> ipFilter = Optional.empty(); if (!serverConfig.getIpFilterRules().isEmpty()) { ipFilter = Optional.of(IpFilteringService.newDecorator(serverConfig.getIpFilterRules())); } if (!serverConfig.isDisableDocService()) { DocServiceBuilder docService = new DocServiceBuilder(); if (!authConfig.getServiceAccountBase64().isEmpty()) { docService.injectedScript("armeria.registerHeaderProvider(function() {\n" + " return firebase.auth().currentUser.getIdToken().then(token => { authorization: 'bearer ' + token });\n" + "});"); } sb.serviceUnder("/internal/docs", internalService(docService.build(), ipFilter, serverConfig)); } SettableHealthChecker settableHealthChecker = new SettableHealthChecker(true); List<HealthChecker> healthCheckers = serverShutDownDelayers.isEmpty() ? ImmutableList.of() : ImmutableList.of(settableHealthChecker); sb.service("/internal/health", internalService(new HttpHealthCheckService(healthCheckers), ipFilter, serverConfig)); sb.service("/internal/dropwizard", internalService(metricsHttpService, ipFilter, serverConfig)); sb.service("/internal/metrics", internalService(new PrometheusExpositionService(collectorRegistry), ipFilter, serverConfig)); if (sslCommonNamesProvider.isPresent()) { SslCommonNamesProvider namesProvider = sslCommonNamesProvider.get(); sb.service("/internal/rpcacls", internalService((ctx, req) -> HttpResponse.of(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, String.join("\n", namesProvider.get())), ipFilter, serverConfig)); } if (!grpcServices.isEmpty()) { GrpcServiceDefinition definition = new GrpcServiceDefinition.Builder().addAllServices(grpcServices) .decorator(Function.identity()).path(serverConfig.getGrpcPath()).build(); grpcServiceDefinitions = ImmutableSet.<GrpcServiceDefinition>builder().addAll(grpcServiceDefinitions) .add(definition).build(); } for (GrpcServiceDefinition definition : grpcServiceDefinitions) { GrpcServiceBuilder serviceBuilder = new GrpcServiceBuilder() .supportedSerializationFormats(GrpcSerializationFormats.values()).enableUnframedRequests(true); definition.services().forEach(serviceBuilder::addService); if (!serverConfig.isDisableGrpcServiceDiscovery()) { serviceBuilder.addService(ProtoReflectionService.newInstance()); } definition.customizer().accept(serviceBuilder); ServiceWithRoutes<HttpRequest, HttpResponse> service = serviceBuilder.build(); if (definition.path().equals("/")) { Optional<SslCommonNamesProvider> sslCommonNamesProvider0 = sslCommonNamesProvider; sb.service(service, s -> decorateService(s.decorate(definition.decorator()), tracing, firebaseAuthorizer, jwtAuthorizer, sslCommonNamesProvider0, serverConfig, authConfig)); } else { sb.serviceUnder(definition.path(), decorateService(service.decorate(definition.decorator()), tracing, firebaseAuthorizer, jwtAuthorizer, sslCommonNamesProvider, serverConfig, authConfig)); } } for (HttpServiceDefinition definition : httpServiceDefinitions) { sb.service(definition.route(), decorateService(definition.service(), tracing, firebaseAuthorizer, jwtAuthorizer, sslCommonNamesProvider, serverConfig, authConfig)); } if (javascriptStaticConfig.getVersion() != 0) { sb.service("/static/jsconfig-" + javascriptStaticConfig.getVersion(), javascriptStaticService.get()); } for (StaticSiteServiceDefinition staticSite : staticSites) { sb.serviceUnder(staticSite.urlRoot(), StaticSiteService.of(staticSite.staticPath(), staticSite.classpathRoot())); } if (ipFilter.isPresent() && !serverConfig.getIpFilterInternalOnly()) { sb.decorator(ipFilter.get()); } if (securityConfig.getHttpsOnly()) { sb.decorator(httpsOnlyServiceFactory.newDecorator()); } sb.decorator(loggingService); sb.meterRegistry(meterRegistry); if (serverConfig.getEnableGracefulShutdown()) { sb.gracefulShutdownTimeout(Duration.ofSeconds(10), Duration.ofSeconds(30)); } postServerCustomizers.forEach((c) -> c.accept(sb)); sb.serverListener(new ServerListener() { @Override public void serverStarting(Server server) { } @Override public void serverStarted(Server server) { } @Override public void serverStopping(Server server) { } @Override public void serverStopped(Server server) { closeOnStopDependencies.forEach(c -> { try { c.close(); } catch (IOException e) { logger.info("Exception closing {}", c); } }); } }); Server server = sb.build(); server.start().whenComplete((unused, t) -> { if (t != null) { logger.error("Error starting server.", t); } else { logger.info("Server started on ports: " + server.activePorts()); } }); Runtime.getRuntime().addShutdownHook(new Thread(() -> { logger.info("Received shutdown signal."); settableHealthChecker.setHealthy(false); if (!serverShutDownDelayers.isEmpty()) { Futures.getUnchecked(Futures.successfulAsList(serverShutDownDelayers.stream() .map(ServerShutDownDelayer::readyForShutdown).collect(toImmutableList()))); } logger.info("Server shutting down."); server.stop().join(); })); if (!fileWatcherBuilder.isEmpty()) { FileWatcher fileWatcher = fileWatcherBuilder.build(); fileWatcher.start(); Runtime.getRuntime().addShutdownHook(new Thread(fileWatcher::close)); } if (monitoringConfig.isReportTraces()) { server.nextEventLoop().scheduleAtFixedRate(stackdriverReporter.get()::flush, 0, monitoringConfig.getTraceReportInterval().getSeconds(), TimeUnit.SECONDS); } return server; }
From source file:org.dvlyyon.nbi.gnmi.GnmiServer.java
License:Open Source License
private Server getTLSServer(GnmiServerContextInf cmd, BindableService service, AuthInterceptor interceptor) throws Exception { int port = cmd.getServerPort(); SslContextBuilder contextBuilder = GrpcSslContexts.forServer(new File(cmd.getServerCACertificate()), new File(cmd.getServerKey())); if (cmd.getClientCACertificate() != null) contextBuilder = contextBuilder.trustManager(new File(cmd.getClientCACertificate())); contextBuilder = cmd.requireClientCert() ? contextBuilder.clientAuth(ClientAuth.REQUIRE) : contextBuilder.clientAuth(ClientAuth.OPTIONAL); server = NettyServerBuilder.forPort(port).sslContext(contextBuilder.build()) .addService(ServerInterceptors.intercept(service, interceptor)).build(); logger.info("Server started, listening on " + port); return server; }
From source file:org.jooby.internal.netty.NettySslContext.java
License:Apache License
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;//www . jav a 2 s . c o m SslContextBuilder scb = SslContextBuilder.forServer(keyStoreCert, keyStoreKey, keyStorePass); if (conf.hasPath("ssl.trust.cert")) { scb.trustManager(toFile(conf.getString("ssl.trust.cert"), tmpdir)); } 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(); }
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); }// www.j a v a 2 s . co m // 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;/*from ww w . j a v a 2 s .c o 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:ratpack.config.internal.module.NettySslContextDeserializer.java
License:Apache License
@SuppressWarnings("Duplicates") @Override//w w w. j a va2 s.c o m public SslContext deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { ObjectNode node = jp.readValueAsTree(); try { String keyStoreFile = node.path("keystoreFile").asText(); String keyStorePassword = node.path("keystorePassword").asText(); String trustStoreFile = node.path("truststoreFile").asText(); String trustStorePassword = node.path("truststorePassword").asText(); if (keyStoreFile.isEmpty()) { throw new IllegalStateException("keystoreFile must be set if any ssl properties are set"); } else if (keyStorePassword.isEmpty()) { throw new IllegalStateException("keystorePassword must be set if any ssl properties are set"); } else if (!trustStoreFile.isEmpty() && trustStorePassword.isEmpty()) { throw new IllegalStateException( "truststorePassword must be specified when truststoreFile is specified"); } KeyManagerFactory keyManagerFactory; try (InputStream is = Files.newInputStream(Paths.get(keyStoreFile))) { keyManagerFactory = SslContexts.keyManagerFactory(is, keyStorePassword.toCharArray()); } SslContextBuilder builder = SslContextBuilder.forServer(keyManagerFactory); if (!trustStoreFile.isEmpty()) { try (InputStream is = Files.newInputStream(Paths.get(trustStoreFile))) { builder.trustManager(SslContexts.trustManagerFactory(is, trustStorePassword.toCharArray())); } } return builder.build(); } catch (GeneralSecurityException ex) { throw Exceptions.uncheck(ex); } }
From source file:reactor.ipc.netty.options.ClientOptions.java
License:Open Source License
/** * Enable default sslContext support and enable further customization via the passed * configurator. The builder will then produce the {@link SslContext} to be passed to * {@link #sslContext(SslContext)}./* w w w . java2s.c o m*/ * * @param configurator builder callback for further customization. * * @return this {@link ClientOptions} */ public ClientOptions sslSupport(Consumer<? super SslContextBuilder> configurator) { Objects.requireNonNull(configurator, "configurator"); try { SslContextBuilder builder = SslContextBuilder.forClient(); configurator.accept(builder); return sslContext(builder.build()); } catch (Exception sslException) { throw Exceptions.bubble(sslException); } }
From source file:reactor.ipc.netty.options.ServerOptions.java
License:Open Source License
/** * Enable SSL service with a self-signed certificate and allows extra * parameterization of the self signed {@link SslContextBuilder}. The builder is * then used to invoke {@link #sslContext(SslContext)}. * * @param configurator the builder callback to setup the self-signed {@link SslContextBuilder} * * @return {@code this}// w w w. j a v a 2s . com */ public ServerOptions sslSelfSigned(Consumer<? super SslContextBuilder> configurator) { Objects.requireNonNull(configurator, "configurator"); SelfSignedCertificate ssc; try { ssc = new SelfSignedCertificate(); SslContextBuilder builder = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()); configurator.accept(builder); return sslContext(builder.build()); } catch (Exception sslException) { throw Exceptions.bubble(sslException); } }