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

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

Introduction

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

Prototype

boolean forServer

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

Click Source Link

Usage

From source file:object.server.ObjectServer.java

public void run(final ConnectionFeedBack connectionFeedBack)
        throws CertificateException, SSLException, InterruptedException, BindException {
    final SslContext sslCtx;
    if (SSL) {//from  w w w. java2  s . com
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    try {
        server = new ServerBootstrap();
        server.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast("deflater", ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP));
                        p.addLast("inflater", ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        p.addLast(new ObjectEncoder(),
                                new ObjectDecoder(ClassResolvers.cacheDisabled(classLoader)),
                                new ObjectServerHandler(connectionFeedBack));
                    }
                });

        // Bind and start to accept incoming connections.
        System.out.println("[ObjectServer]\t " + "Server listen to port " + PORT);
        server.bind(PORT).sync().channel().closeFuture().sync();
    } catch (InterruptedException ex) {
        throw new RuntimeException("bind failed..");
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}

From source file:org.apache.activemq.artemis.core.remoting.impl.ssl.SSLSupport.java

License:Apache License

public SslContext createNettyContext() throws Exception {
    KeyStore keyStore = SSLSupport.loadKeystore(keystoreProvider, keystorePath, keystorePassword);
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePassword.toCharArray());
    return SslContextBuilder.forServer(keyManagerFactory).sslProvider(SslProvider.valueOf(sslProvider))
            .trustManager(loadTrustManagerFactory()).build();
}

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 a v  a 2s .  co m

    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.drill.exec.ssl.SSLConfigServer.java

License:Apache License

@Override
public SslContext initNettySslContext() throws DrillException {
    final SslContext sslCtx;

    if (!userSslEnabled) {
        return null;
    }//w  w w . j a va2s .com

    KeyManagerFactory kmf;
    TrustManagerFactory tmf;
    try {
        if (keyStorePath.isEmpty()) {
            throw new DrillException("No Keystore provided.");
        }
        kmf = initializeKeyManagerFactory();
        tmf = initializeTrustManagerFactory();
        sslCtx = SslContextBuilder.forServer(kmf).trustManager(tmf).protocols(protocol)
                .sslProvider(getProvider()).build(); // Will throw an exception if the key password is not correct
    } catch (Exception e) {
        // Catch any SSL initialization Exceptions here and abort.
        throw new DrillException(new StringBuilder().append("SSL is enabled but cannot be initialized - ")
                .append("[ ").append(e.getMessage()).append("]. ").toString());
    }
    this.nettySslContext = sslCtx;
    return sslCtx;
}

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();//w  ww . j a va  2  s.co  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.TestGRPCServer.java

License:Apache License

/**
 * Starts the gRPC server @localhost:port.
 *///from  ww  w  .j a  v  a2  s  . c o  m
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();//w ww. j a v  a  2  s  .  c  om

    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.apache.tinkerpop.gremlin.server.AbstractChannelizer.java

License:Apache License

private SslContext createSSLContext(final Settings settings) {
    final Settings.SslSettings sslSettings = settings.ssl;

    if (sslSettings.getSslContext().isPresent()) {
        logger.info("Using the SslContext override");
        return sslSettings.getSslContext().get();
    }/*from www.jav  a2s  . c  o  m*/

    final SslProvider provider = SslProvider.JDK;

    final SslContextBuilder builder;

    // if the config doesn't contain a cert or key then use a self signed cert - not suitable for production
    if (null == sslSettings.keyCertChainFile || null == sslSettings.keyFile) {
        try {
            logger.warn("Enabling SSL with self-signed certificate (NOT SUITABLE FOR PRODUCTION)");
            final SelfSignedCertificate ssc = new SelfSignedCertificate();
            builder = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
        } catch (CertificateException ce) {
            logger.error("There was an error creating the self-signed certificate for SSL - SSL is not enabled",
                    ce);
            return null;
        }
    } else {
        final File keyCertChainFile = new File(sslSettings.keyCertChainFile);
        final File keyFile = new File(sslSettings.keyFile);
        final File trustCertChainFile = null == sslSettings.trustCertChainFile ? null
                : new File(sslSettings.trustCertChainFile);

        // note that keyPassword may be null here if the keyFile is not password-protected. passing null to
        // trustManager is also ok (default will be used)
        builder = SslContextBuilder.forServer(keyCertChainFile, keyFile, sslSettings.keyPassword)
                .trustManager(trustCertChainFile);
    }

    builder.sslProvider(provider);

    try {
        return builder.build();
    } catch (SSLException ssle) {
        logger.error("There was an error enabling SSL", ssle);
        return null;
    }
}

From source file:org.apache.tinkerpop.gremlin.server.GremlinServerIntegrateTest.java

License:Apache License

private static SslContext createServerSslContext() {
    final SslProvider provider = SslProvider.JDK;

    try {/*  w  ww. j av  a 2 s  . c o  m*/
        // this is not good for production - just testing
        final SelfSignedCertificate ssc = new SelfSignedCertificate();
        return SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider).build();
    } catch (Exception ce) {
        throw new RuntimeException("Couldn't setup self-signed certificate for test");
    }
}

From source file:org.betawares.jorre.Server.java

License:Open Source License

/**
 * Starts the Server with the specified {@link Connection} settings.
 * //from w  w  w.  j  av a 2  s.com
 * @param connection  a {@link Connection} instance specifying the connection settings
 * 
 * @throws Exception  thrown if there is an error starting the server
 */
public void start(Connection connection) throws Exception {

    SslContext sslCtx;

    if (connection.isSSL()) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) {
                    if (sslCtx != null) {
                        ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()));
                    }
                    ch.pipeline()
                            .addLast(new ObjectDecoder(10 * 1024 * 1024, ClassResolvers.cacheDisabled(null)));
                    ch.pipeline().addLast(encoder);
                    ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(connection.getIdleTimeout(),
                            connection.getIdlePingTime(), 0, TimeUnit.MILLISECONDS));
                    ch.pipeline().addLast(handlersExecutor, "heartbeatHandler",
                            new ServerHeartbeatHandler(Server.this));
                    ch.pipeline().addLast("pingMessageHandler", pingMessageHandler);
                    ch.pipeline().addLast("pongMessageHandler", pongMessageHandler);

                    ch.pipeline().addLast("connectionHandler", new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            clients.add(ctx.channel());
                            ctx.pipeline().remove(this);
                            super.channelActive(ctx);
                        }
                    });
                    ch.pipeline().addLast(handlersExecutor, "serverMessageHandler", serverRequestHandler);
                    ch.pipeline().addLast("exceptionHandler", exceptionHandler);
                }
            });
    bootstrap.bind(connection.getPort()).sync();

}