Example usage for io.netty.handler.ssl ClientAuth OPTIONAL

List of usage examples for io.netty.handler.ssl ClientAuth OPTIONAL

Introduction

In this page you can find the example usage for io.netty.handler.ssl ClientAuth OPTIONAL.

Prototype

ClientAuth OPTIONAL

To view the source code for io.netty.handler.ssl ClientAuth OPTIONAL.

Click Source Link

Document

Indicates that the javax.net.ssl.SSLEngine will request client authentication.

Usage

From source file:io.crate.protocols.ssl.SslConfiguration.java

public static SslContext buildSslContext(Settings settings) {
    try {/*from w  w w .  j a v  a  2s.  c om*/
        KeyStoreSettings keyStoreSettings = new KeyStoreSettings(settings);

        Optional<TrustStoreSettings> trustStoreSettings = TrustStoreSettings.tryLoad(settings);
        TrustManager[] trustManagers = null;
        if (trustStoreSettings.isPresent()) {
            trustManagers = trustStoreSettings.get().trustManagers;
        }

        // Use the newest SSL standard which is (at the time of writing) TLSv1.2
        // If we just specify "TLS" here, it depends on the JVM implementation which version we'll get.
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(keyStoreSettings.keyManagers, trustManagers, null);
        SSLContext.setDefault(sslContext);

        List<String> enabledCiphers = Arrays.asList(sslContext.createSSLEngine().getEnabledCipherSuites());

        final X509Certificate[] keystoreCerts = keyStoreSettings.exportServerCertChain();
        final PrivateKey privateKey = keyStoreSettings.exportDecryptedKey();

        X509Certificate[] trustedCertificates = keyStoreSettings.exportRootCertificates();
        if (trustStoreSettings.isPresent()) {
            trustedCertificates = trustStoreSettings.get().exportRootCertificates(trustedCertificates);
        }

        final SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(privateKey, keystoreCerts)
                .ciphers(enabledCiphers).applicationProtocolConfig(ApplicationProtocolConfig.DISABLED)
                .clientAuth(ClientAuth.OPTIONAL).sessionCacheSize(0).sessionTimeout(0).startTls(false)
                .sslProvider(SslProvider.JDK);

        if (trustedCertificates != null && trustedCertificates.length > 0) {
            sslContextBuilder.trustManager(trustedCertificates);
        }

        return sslContextBuilder.build();

    } catch (SslConfigurationException e) {
        throw e;
    } catch (Exception e) {
        throw new SslConfigurationException("Failed to build SSL configuration", e);
    }
}

From source file:org.apache.rocketmq.remoting.netty.TlsHelper.java

License:Apache License

public static SslContext buildSslContext(boolean forClient) throws IOException, CertificateException {
    File configFile = new File(TlsSystemConfig.tlsConfigFile);
    extractTlsConfigFromFile(configFile);
    logTheFinalUsedTlsConfig();//from   www  .ja  v  a2s . c  o  m

    SslProvider provider;
    if (OpenSsl.isAvailable()) {
        provider = SslProvider.OPENSSL;
        LOGGER.info("Using OpenSSL provider");
    } else {
        provider = SslProvider.JDK;
        LOGGER.info("Using JDK SSL provider");
    }

    if (forClient) {
        if (tlsTestModeEnable) {
            return SslContextBuilder.forClient().sslProvider(SslProvider.JDK)
                    .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } else {
            SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(SslProvider.JDK);

            if (!tlsClientAuthServer) {
                sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            } else {
                if (!isNullOrEmpty(tlsClientTrustCertPath)) {
                    sslContextBuilder.trustManager(new File(tlsClientTrustCertPath));
                }
            }

            return sslContextBuilder
                    .keyManager(
                            !isNullOrEmpty(tlsClientCertPath) ? new FileInputStream(tlsClientCertPath) : null,
                            !isNullOrEmpty(tlsClientKeyPath)
                                    ? decryptionStrategy.decryptPrivateKey(tlsClientKeyPath, true)
                                    : null,
                            !isNullOrEmpty(tlsClientKeyPassword) ? tlsClientKeyPassword : null)
                    .build();
        }
    } else {

        if (tlsTestModeEnable) {
            SelfSignedCertificate selfSignedCertificate = new SelfSignedCertificate();
            return SslContextBuilder
                    .forServer(selfSignedCertificate.certificate(), selfSignedCertificate.privateKey())
                    .sslProvider(SslProvider.JDK).clientAuth(ClientAuth.OPTIONAL).build();
        } else {
            SslContextBuilder sslContextBuilder = SslContextBuilder
                    .forServer(
                            !isNullOrEmpty(tlsServerCertPath) ? new FileInputStream(tlsServerCertPath) : null,
                            !isNullOrEmpty(tlsServerKeyPath)
                                    ? decryptionStrategy.decryptPrivateKey(tlsServerKeyPath, false)
                                    : null,
                            !isNullOrEmpty(tlsServerKeyPassword) ? tlsServerKeyPassword : null)
                    .sslProvider(provider);

            if (!tlsServerAuthClient) {
                sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            } else {
                if (!isNullOrEmpty(tlsServerTrustCertPath)) {
                    sslContextBuilder.trustManager(new File(tlsServerTrustCertPath));
                }
            }

            sslContextBuilder.clientAuth(parseClientAuthMode(tlsServerNeedClientAuth));
            return sslContextBuilder.build();
        }
    }
}

From source file:org.curioswitch.common.server.framework.ServerModule.java

License:Open Source License

@SuppressWarnings("FutureReturnValueIgnored")
@Provides//from  ww w  . ja v a 2s  .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.graylog2.plugin.inputs.transports.AbstractTcpTransport.java

License:Open Source License

private Callable<ChannelHandler> getSslHandlerCallable(MessageInput input) {
    final File certFile;
    final File keyFile;
    if (tlsCertFile.exists() && tlsKeyFile.exists()) {
        certFile = tlsCertFile;/*from  w w w  .j  a  v  a2  s . c o  m*/
        keyFile = tlsKeyFile;
    } else {
        LOG.warn(
                "TLS key file or certificate file does not exist, creating a self-signed certificate for input [{}/{}].",
                input.getName(), input.getId());

        final String tmpDir = System.getProperty("java.io.tmpdir");
        checkState(tmpDir != null, "The temporary directory must not be null!");
        final Path tmpPath = Paths.get(tmpDir);
        if (!Files.isDirectory(tmpPath) || !Files.isWritable(tmpPath)) {
            throw new IllegalStateException(
                    "Couldn't write to temporary directory: " + tmpPath.toAbsolutePath());
        }

        try {
            final SelfSignedCertificate ssc = new SelfSignedCertificate(
                    configuration.getString(CK_BIND_ADDRESS) + ":" + configuration.getString(CK_PORT));
            certFile = ssc.certificate();
            keyFile = ssc.privateKey();
        } catch (CertificateException e) {
            final String msg = String.format(Locale.ENGLISH,
                    "Problem creating a self-signed certificate for input [%s/%s].", input.getName(),
                    input.getId());
            throw new IllegalStateException(msg, e);
        }
    }

    final ClientAuth clientAuth;
    switch (tlsClientAuth) {
    case TLS_CLIENT_AUTH_DISABLED:
        LOG.debug("Not using TLS client authentication");
        clientAuth = ClientAuth.NONE;
        break;
    case TLS_CLIENT_AUTH_OPTIONAL:
        LOG.debug("Using optional TLS client authentication");
        clientAuth = ClientAuth.OPTIONAL;
        break;
    case TLS_CLIENT_AUTH_REQUIRED:
        LOG.debug("Using mandatory TLS client authentication");
        clientAuth = ClientAuth.REQUIRE;
        break;
    default:
        throw new IllegalArgumentException("Unknown TLS client authentication mode: " + tlsClientAuth);
    }

    return buildSslHandlerCallable(nettyTransportConfiguration.getTlsProvider(), certFile, keyFile,
            tlsKeyPassword, clientAuth, tlsClientAuthCertFile);
}

From source file:org.graylog2.plugin.inputs.transports.AbstractTcpTransport.java

License:Open Source License

private Callable<ChannelHandler> buildSslHandlerCallable(SslProvider tlsProvider, File certFile, File keyFile,
        String password, ClientAuth clientAuth, File clientAuthCertFile) {
    return new Callable<ChannelHandler>() {
        @Override//from  w w  w . ja va2 s . co  m
        public ChannelHandler call() throws Exception {
            try {
                return new SslHandler(createSslEngine());
            } catch (SSLException e) {
                LOG.error(
                        "Error creating SSL context. Make sure the certificate and key are in the correct format: cert=X.509 key=PKCS#8");
                throw e;
            }
        }

        private SSLEngine createSslEngine() throws IOException, CertificateException {
            final X509Certificate[] clientAuthCerts;
            if (EnumSet.of(ClientAuth.OPTIONAL, ClientAuth.REQUIRE).contains(clientAuth)) {
                if (clientAuthCertFile.exists()) {
                    clientAuthCerts = KeyUtil.loadCertificates(clientAuthCertFile.toPath()).stream()
                            .filter(certificate -> certificate instanceof X509Certificate)
                            .map(certificate -> (X509Certificate) certificate).toArray(X509Certificate[]::new);
                } else {
                    LOG.warn(
                            "Client auth configured, but no authorized certificates / certificate authorities configured");
                    clientAuthCerts = null;
                }
            } else {
                clientAuthCerts = null;
            }

            final SslContext sslContext = SslContextBuilder
                    .forServer(certFile, keyFile, Strings.emptyToNull(password)).sslProvider(tlsProvider)
                    .clientAuth(clientAuth).trustManager(clientAuthCerts).build();

            // TODO: Use byte buffer allocator of channel
            return sslContext.newEngine(ByteBufAllocator.DEFAULT);
        }
    };
}

From source file:org.springframework.boot.web.embedded.netty.SslServerCustomizer.java

License:Apache License

protected SslContextBuilder getContextBuilder() {
    SslContextBuilder builder = SslContextBuilder
            .forServer(getKeyManagerFactory(this.ssl, this.sslStoreProvider))
            .trustManager(getTrustManagerFactory(this.ssl, this.sslStoreProvider));
    if (this.ssl.getEnabledProtocols() != null) {
        builder.protocols(this.ssl.getEnabledProtocols());
    }/*  w w  w .java  2s. c  om*/
    if (this.ssl.getCiphers() != null) {
        builder.ciphers(Arrays.asList(this.ssl.getCiphers()));
    }
    if (this.ssl.getClientAuth() == Ssl.ClientAuth.NEED) {
        builder.clientAuth(ClientAuth.REQUIRE);
    } else if (this.ssl.getClientAuth() == Ssl.ClientAuth.WANT) {
        builder.clientAuth(ClientAuth.OPTIONAL);
    }
    return builder;
}