Example usage for io.netty.handler.ssl SslContextBuilder clientAuth

List of usage examples for io.netty.handler.ssl SslContextBuilder clientAuth

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslContextBuilder clientAuth.

Prototype

ClientAuth clientAuth

To view the source code for io.netty.handler.ssl SslContextBuilder clientAuth.

Click Source Link

Usage

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;
        }/* w  w w.  j a  va 2  s.c  om*/

        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.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 {/*w  w w.j  a  va2s. com*/
            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));
}

From source file:com.yahoo.pulsar.discovery.service.ServiceChannelInitializer.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);
        // allows insecure connection
        builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
        SslContext sslCtx = builder.clientAuth(ClientAuth.OPTIONAL).build();
        ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc()));
    }/* ww  w  .  j  a v a  2 s  .  c  o  m*/
    ch.pipeline().addLast("frameDecoder",
            new PulsarLengthFieldFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4));
    ch.pipeline().addLast("handler", new ServerConnection(discoveryService));
}

From source file:io.grpc.examples.helloworldtls.HelloWorldServerTls.java

License:Apache License

private SslContextBuilder getSslContextBuilder() {
    SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(new File(certChainFilePath),
            new File(privateKeyFilePath));
    if (trustCertCollectionFilePath != null) {
        sslClientContextBuilder.trustManager(new File(trustCertCollectionFilePath));
        sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);
    }// ww w . j  a  v a  2 s .  c o  m
    return GrpcSslContexts.configure(sslClientContextBuilder);
}

From source file:net.devh.boot.grpc.server.serverfactory.NettyGrpcServerFactory.java

License:Open Source License

@Override
// Keep this in sync with ShadedNettyGrpcServerFactory#configureSecurity
protected void configureSecurity(final NettyServerBuilder builder) {
    final Security security = this.properties.getSecurity();
    if (security.isEnabled()) {
        final File certificateChainFile = toCheckedFile("certificateChain", security.getCertificateChainPath());
        final File privateKeyFile = toCheckedFile("privateKey", security.getPrivateKeyPath());
        final SslContextBuilder sslContextBuilder = GrpcSslContexts.forServer(certificateChainFile,
                privateKeyFile);/*from  w  ww  .j av a2 s .c o m*/

        if (security.getClientAuth() != ClientAuth.NONE) {
            sslContextBuilder.clientAuth(of(security.getClientAuth()));

            final String trustCertCollectionPath = security.getTrustCertCollectionPath();
            if (trustCertCollectionPath != null && !trustCertCollectionPath.isEmpty()) {
                final File trustCertCollectionFile = toCheckedFile("trustCertCollection",
                        trustCertCollectionPath);
                sslContextBuilder.trustManager(trustCertCollectionFile);
            }
        }

        try {
            builder.sslContext(sslContextBuilder.build());
        } catch (final SSLException e) {
            throw new IllegalStateException("Failed to create ssl context for grpc server", e);
        }
    }
}

From source file:org.apache.bookkeeper.tls.TLSContextFactory.java

License:Apache License

private void createServerContext(AbstractConfiguration conf)
        throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException, InvalidKeySpecException, IllegalArgumentException {
    final SslContextBuilder sslContextBuilder;
    final ServerConfiguration serverConf;
    final SslProvider provider;
    final boolean clientAuthentication;

    // get key-file and trust-file locations and passwords
    if (!(conf instanceof ServerConfiguration)) {
        throw new SecurityException("Server configruation not provided");
    }//w  w w .j  av  a  2  s.c  om

    serverConf = (ServerConfiguration) conf;
    provider = getTLSProvider(serverConf.getTLSProvider());
    clientAuthentication = serverConf.getTLSClientAuthentication();

    switch (KeyStoreType.valueOf(serverConf.getTLSKeyStoreType())) {
    case PEM:
        final String keyPassword;

        if (Strings.isNullOrEmpty(serverConf.getTLSKeyStore())) {
            throw new SecurityException("Key path is required");
        }

        if (Strings.isNullOrEmpty(serverConf.getTLSCertificatePath())) {
            throw new SecurityException("Certificate path is required");
        }

        if (!Strings.isNullOrEmpty(serverConf.getTLSKeyStorePasswordPath())) {
            keyPassword = getPasswordFromFile(serverConf.getTLSKeyStorePasswordPath());
        } else {
            keyPassword = null;
        }

        sslContextBuilder = SslContextBuilder
                .forServer(new File(serverConf.getTLSCertificatePath()), new File(serverConf.getTLSKeyStore()),
                        keyPassword)
                .ciphers(null).sessionCacheSize(0).sessionTimeout(0).sslProvider(provider).startTls(true);

        break;
    case JKS:
        // falling thru, same as PKCS12
    case PKCS12:
        KeyManagerFactory kmf = initKeyManagerFactory(serverConf.getTLSKeyStoreType(),
                serverConf.getTLSKeyStore(), serverConf.getTLSKeyStorePasswordPath());

        sslContextBuilder = SslContextBuilder.forServer(kmf).ciphers(null).sessionCacheSize(0).sessionTimeout(0)
                .sslProvider(provider).startTls(true);

        break;
    default:
        throw new SecurityException("Invalid Keyfile type" + serverConf.getTLSKeyStoreType());
    }

    if (clientAuthentication) {
        sslContextBuilder.clientAuth(ClientAuth.REQUIRE);

        switch (KeyStoreType.valueOf(serverConf.getTLSTrustStoreType())) {
        case PEM:
            if (Strings.isNullOrEmpty(serverConf.getTLSTrustStore())) {
                throw new SecurityException("CA Certificate chain is required");
            }
            sslContextBuilder.trustManager(new File(serverConf.getTLSTrustStore()));
            break;
        case JKS:
            // falling thru, same as PKCS12
        case PKCS12:
            TrustManagerFactory tmf = initTrustManagerFactory(serverConf.getTLSTrustStoreType(),
                    serverConf.getTLSTrustStore(), serverConf.getTLSTrustStorePasswordPath());
            sslContextBuilder.trustManager(tmf);
            break;
        default:
            throw new SecurityException("Invalid Truststore type" + serverConf.getTLSTrustStoreType());
        }
    }

    sslContext = sslContextBuilder.build();
}

From source file:org.apache.nifi.processors.grpc.ListenGRPC.java

License:Apache License

@OnScheduled
public void startServer(final ProcessContext context) throws NoSuchAlgorithmException, IOException,
        KeyStoreException, CertificateException, UnrecoverableKeyException {
    final ComponentLog logger = getLogger();
    // gather configured properties
    final Integer port = context.getProperty(PROP_SERVICE_PORT).asInteger();
    final Boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean();
    final Integer flowControlWindow = context.getProperty(PROP_FLOW_CONTROL_WINDOW).asDataSize(DataUnit.B)
            .intValue();/*from ww w  .  jav a 2  s  .c o  m*/
    final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue();
    final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslContextService == null ? null
            : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE);
    final Pattern authorizedDnPattern = Pattern
            .compile(context.getProperty(PROP_AUTHORIZED_DN_PATTERN).getValue());
    final FlowFileIngestServiceInterceptor callInterceptor = new FlowFileIngestServiceInterceptor(getLogger());
    callInterceptor.enforceDNPattern(authorizedDnPattern);

    final FlowFileIngestService flowFileIngestService = new FlowFileIngestService(getLogger(),
            sessionFactoryReference, context);
    NettyServerBuilder serverBuilder = NettyServerBuilder.forPort(port)
            .addService(ServerInterceptors.intercept(flowFileIngestService, callInterceptor))
            // default (de)compressor registries handle both plaintext and gzip compressed messages
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
            .flowControlWindow(flowControlWindow).maxMessageSize(maxMessageSize);

    if (useSecure && sslContext != null) {
        // construct key manager
        if (StringUtils.isBlank(sslContextService.getKeyStoreFile())) {
            throw new IllegalStateException(
                    "SSL is enabled, but no keystore has been configured. You must configure a keystore.");
        }

        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
        final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType());
        try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) {
            keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray());
        }
        keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray());

        SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(keyManagerFactory);

        // if the trust store is configured, then client auth is required.
        if (StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
            final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) {
                trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory);
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
        } else {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.NONE);
        }
        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
        serverBuilder = serverBuilder.sslContext(sslContextBuilder.build());
    }
    logger.info("Starting gRPC server on port: {}", new Object[] { port.toString() });
    this.server = serverBuilder.build().start();
}

From source file:org.apache.nifi.processors.grpc.TestGRPCClient.java

License:Apache License

/**
 * Build a channel with the given host and port and optional ssl properties.
 *
 * @param host          the host to establish a connection with
 * @param port          the port on which to communicate with the host
 * @param sslProperties the properties by which to establish an ssl connection
 * @return a constructed channel/*  w  w w  . ja v  a 2s .c om*/
 */
public static ManagedChannel buildChannel(final String host, final int port,
        final Map<String, String> sslProperties) throws NoSuchAlgorithmException, KeyStoreException,
        IOException, CertificateException, UnrecoverableKeyException {
    NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port).directExecutor()
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance()).userAgent("testAgent");

    if (sslProperties != null) {
        SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

        if (sslProperties.get(StandardSSLContextService.KEYSTORE.getName()) != null) {
            final KeyManagerFactory keyManager = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            final KeyStore keyStore = KeyStore
                    .getInstance(sslProperties.get(StandardSSLContextService.KEYSTORE_TYPE.getName()));
            final String keyStoreFile = sslProperties.get(StandardSSLContextService.KEYSTORE.getName());
            final String keyStorePassword = sslProperties
                    .get(StandardSSLContextService.KEYSTORE_PASSWORD.getName());
            try (final InputStream is = new FileInputStream(keyStoreFile)) {
                keyStore.load(is, keyStorePassword.toCharArray());
            }
            keyManager.init(keyStore, keyStorePassword.toCharArray());
            sslContextBuilder = sslContextBuilder.keyManager(keyManager);
        }

        if (sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()) != null) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            final KeyStore trustStore = KeyStore
                    .getInstance(sslProperties.get(StandardSSLContextService.TRUSTSTORE_TYPE.getName()));
            final String trustStoreFile = sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName());
            final String trustStorePassword = sslProperties
                    .get(StandardSSLContextService.TRUSTSTORE_PASSWORD.getName());
            try (final InputStream is = new FileInputStream(trustStoreFile)) {
                trustStore.load(is, trustStorePassword.toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory);
        }

        final String clientAuth = sslProperties.get(NEED_CLIENT_AUTH);
        if (clientAuth == null) {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
        } else {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.valueOf(clientAuth));
        }
        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
        channelBuilder = channelBuilder.sslContext(sslContextBuilder.build());
    } else {
        channelBuilder.usePlaintext(true);
    }
    return channelBuilder.build();
}

From source file:org.apache.nifi.processors.grpc.TestGRPCServer.java

License:Apache License

/**
 * Starts the gRPC server @localhost:port.
 *///from w  w w  .  ja  v a  2 s.c om
public int start(final int port) throws Exception {
    final NettyServerBuilder nettyServerBuilder = NettyServerBuilder.forPort(port).directExecutor()
            .addService(clazz.newInstance()).compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance());

    if (this.sslProperties != null) {
        if (sslProperties.get(StandardSSLContextService.KEYSTORE.getName()) == null) {
            throw new RuntimeException("You must configure a keystore in order to use SSL with gRPC.");
        }

        final KeyManagerFactory keyManager = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        final KeyStore keyStore = KeyStore
                .getInstance(sslProperties.get(StandardSSLContextService.KEYSTORE_TYPE.getName()));
        final String keyStoreFile = sslProperties.get(StandardSSLContextService.KEYSTORE.getName());
        final String keyStorePassword = sslProperties
                .get(StandardSSLContextService.KEYSTORE_PASSWORD.getName());
        try (final InputStream is = new FileInputStream(keyStoreFile)) {
            keyStore.load(is, keyStorePassword.toCharArray());
        }
        keyManager.init(keyStore, keyStorePassword.toCharArray());
        SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(keyManager);

        if (sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()) != null) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            final KeyStore trustStore = KeyStore
                    .getInstance(sslProperties.get(StandardSSLContextService.TRUSTSTORE_TYPE.getName()));
            final String trustStoreFile = sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName());
            final String trustStorePassword = sslProperties
                    .get(StandardSSLContextService.TRUSTSTORE_PASSWORD.getName());
            try (final InputStream is = new FileInputStream(trustStoreFile)) {
                trustStore.load(is, trustStorePassword.toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory);
        }

        final String clientAuth = sslProperties.get(NEED_CLIENT_AUTH);
        if (clientAuth == null) {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
        } else {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.valueOf(clientAuth));
        }
        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
        nettyServerBuilder.sslContext(sslContextBuilder.build());
    }

    server = nettyServerBuilder.build().start();
    final int actualPort = server.getPort();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            // Use stderr here since the logger may have been reset by its JVM shutdown hook.
            System.err.println("*** shutting down gRPC server since JVM is shutting down");
            TestGRPCServer.this.stop();
            System.err.println("*** server shut down");
        }
    });
    return actualPort;
}

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 w ww. java 2  s  .  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();
        }
    }
}