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: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/*  w  w w . j  av  a  2  s.  c  o  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.iotivity.cloud.base.server.Server.java

License:Open Source License

public void startServer(boolean tlsMode) throws CertificateException, SSLException, InterruptedException {

    try {/*  ww  w . ja va2 s  . c o  m*/
        if (tlsMode)
            Log.i("Server starts with TLS!");

        if (tlsMode == true) {

            File serverCert = new File(OICConstants.CLOUD_CERT_FILE);

            File serverKey = new File(OICConstants.CLOUD_KEY_FILE);

            mSslContext = SslContextBuilder.forServer(serverCert, serverKey).build();
        }

        ServerBootstrap b = new ServerBootstrap();
        b.group(acceptorGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));

        b.childHandler(mServerInitializer);

        b.bind(mInetSocketAddress).sync();
    } finally {
    }
}

From source file:org.jboss.aerogear.webpush.netty.WebPushNettyServer.java

License:Apache License

private static SslContext createSslContext(final WebPushServerConfig config) throws Exception {
    if (config.useEndpointTls()) {
        return SslContextBuilder.forServer(config.cert(), config.privateKey()).sslProvider(SslProvider.JDK)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(protocol(config),
                        SelectorFailureBehavior.FATAL_ALERT, SelectedListenerFailureBehavior.FATAL_ALERT,
                        ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))
                .build();/*  w ww  . ja va2  s .com*/
    }
    return null;
}

From source file:org.jdiameter.client.impl.transport.tls.netty.SslContextFactory.java

License:Open Source License

public static SslContext getSslContextForServer(Configuration config) throws SSLException, Exception {
    SslContext sslContext = SslContextBuilder.forServer(getKeyManagerFactory(config))
            .trustManager(getTrustManagerFactory(config)).build();
    return sslContext;
}

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;//from  ww w . j a  v 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.kaazing.messaging.driver.transport.netty.tcp.NettyTransportContext.java

License:Apache License

public NettyTransportContext() {
    super();// ww w.ja v a  2 s  . c o m

    if (USE_SSL) {
        SelfSignedCertificate ssc = null;
        try {
            ssc = new SelfSignedCertificate();
            serverSslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
            clientSslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .build();
        } catch (CertificateException e) {
            LOGGER.error("CertificateException", e);
            throw new IllegalArgumentException("Error creating transport context", e);
        } catch (SSLException e) {
            LOGGER.error("SSLException", e);
            throw new IllegalArgumentException("Error creating transport context", e);
        }
    } else {
        serverSslCtx = null;
        clientSslCtx = null;
    }

    // Configure the server.
    serverBossGroup = new NioEventLoopGroup(1);
    serverWorkerGroup = new NioEventLoopGroup();

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(serverBossGroup, serverWorkerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    final ChannelPipeline p = ch.pipeline();
                    if (serverSslCtx != null) {
                        p.addLast(serverSslCtx.newHandler(ch.alloc()));
                    }
                    p.addLast(new LengthFieldBasedFrameDecoder(1000000, 0, 4, 0, 4));
                    serverReceivingTransportsLock.readLock().lock();
                    try {
                        serverReceivingTransports.forEach((nettyReceivingTransport) -> {
                            if (ch.localAddress().equals(nettyReceivingTransport.getInetSocketAddress())
                                    || nettyReceivingTransport.isInAddrAny()
                                            && ch.localAddress().getPort() == nettyReceivingTransport
                                                    .getInetSocketAddress().getPort()) {
                                p.addLast(nettyReceivingTransport.getNettyChannelHandler());
                            }
                        });
                    } finally {
                        serverReceivingTransportsLock.readLock().unlock();
                    }

                }
            });

    bootstrap = new Bootstrap();
    group = new NioEventLoopGroup();
    bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    if (clientSslCtx != null) {
                        p.addLast(clientSslCtx.newHandler(ch.alloc()));
                    }
                }
            });
}

From source file:org.neo4j.bolt.BoltKernelExtension.java

License:Open Source License

private SslContext createSslContext(Config config, Log log, HostnamePort address) {
    try {//  w  ww . ja v  a2s. c  om
        KeyStoreInformation keyStore = createKeyStore(config, log, address);
        return SslContextBuilder.forServer(keyStore.getCertificatePath(), keyStore.getPrivateKeyPath()).build();
    } catch (IOException | OperatorCreationException | GeneralSecurityException e) {
        throw new RuntimeException(
                "Failed to initilize SSL encryption support, which is required to start this "
                        + "connector. Error was: " + e.getMessage(),
                e);
    }
}

From source file:org.openhab.io.mqttembeddedbroker.internal.EmbeddedBrokerService.java

License:Open Source License

/**
 * For TLS connections we need to setup a keystore and provide Moquette/Netty with an {@link SslContext}.
 * <p>/*  w ww  . ja  v a 2s  .co m*/
 * If a context is requested by Moquette, this creator
 * will use the bundled "serverkeystore.keystore" with password "openhab".
 *
 * @return An SslContext creator (not be confused with javas SSLContext).
 */
ISslContextCreator nettySSLcontextCreator() {
    return () -> {
        try {
            InputStream inputStream = getClass().getClassLoader()
                    .getResourceAsStream("serverkeystore.keystore");
            KeyStore keyStore = KeyStore.getInstance("jks");
            keyStore.load(inputStream, "openhab".toCharArray());
            KeyManagerFactory factory = KeyManagerFactory.getInstance("SunX509");
            factory.init(keyStore, "openhab".toCharArray());
            return SslContextBuilder.forServer(factory).build();
        } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException
                | UnrecoverableKeyException e) {
            logger.warn("Failed to create an SSL context");
            return null;
        }
    };
}

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);
        }/*from  w ww .jav  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.pidome.server.system.network.sockets.SocketBase.java

/**
 * Returns a Netty compatible SSL Context
 * @return SSL context//from   w  w w  .j  a v  a2s  . c o  m
 * @throws ConfigPropertiesException When SSL is not available.
 */
protected SslContextBuilder getNettySSLContext() throws ConfigPropertiesException {
    if (CertGen.available) {
        try {

            KeyStore ks = KeyStore.getInstance("JKS");
            File kf = new File(SystemConfig.getProperty("system", "server.keystore"));
            ks.load(new FileInputStream(kf),
                    System.getProperty("javax.net.ssl.keyStorePassword").toCharArray());

            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, System.getProperty("javax.net.ssl.keyStorePassword").toCharArray());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(ks);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

            return SslContextBuilder.forServer(kmf).trustManager(tmf);

        } catch (KeyStoreException | ConfigPropertiesException | NoSuchAlgorithmException | IOException
                | CertificateException | UnrecoverableKeyException | KeyManagementException ex) {
            throw new ConfigPropertiesException(ex);
        }
    } else {
        throw new ConfigPropertiesException("SSL configured but not available, SSL http wil not start");
    }
}