Example usage for io.netty.handler.ssl.util SelfSignedCertificate SelfSignedCertificate

List of usage examples for io.netty.handler.ssl.util SelfSignedCertificate SelfSignedCertificate

Introduction

In this page you can find the example usage for io.netty.handler.ssl.util SelfSignedCertificate SelfSignedCertificate.

Prototype

public SelfSignedCertificate() throws CertificateException 

Source Link

Document

Creates a new instance.

Usage

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();//  ww w.j  a  va 2s.  co  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.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   ww  w  .  ja v 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 {//from w  w w  .j a  v  a2s. 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.artJava.chat.SecureChatServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    //SelfSignedCertificate
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    ////from  w w  w .  jav a2  s.  c  o  m
    SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();//
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new SecureChatServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
        //bindchannnel
        //syncfuture futurefuture
        //channel futureiochannel
        //closefuture future
        //

    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.atmosphere.nettosphere.test.NettyAtmosphereTest.java

License:Apache License

@Test
public void nettySslContextTest() throws Exception {
    final CountDownLatch l = new CountDownLatch(1);

    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());

    Config config = new Config.Builder().port(port).host("127.0.0.1").sslContext(sslCtx)
            .resource(new Handler() {

                @Override//  w w w .  j  a v a 2s . c  om
                public void handle(AtmosphereResource r) {
                    r.getResponse().write("Hello World from Nettosphere").closeStreamOrWriter();
                }
            }).build();

    server = new Nettosphere.Builder().config(config).build();
    assertNotNull(server);
    server.start();

    AsyncHttpClient c = new AsyncHttpClient(
            new AsyncHttpClientConfig.Builder().setAcceptAnyCertificate(true).build());
    try {
        final AtomicReference<String> response = new AtomicReference<String>();
        WebSocket webSocket = c.prepareGet("wss://127.0.0.1:" + port)
                .execute(new WebSocketUpgradeHandler.Builder().build()).get();
        assertNotNull(webSocket);
        webSocket.addWebSocketListener(new WebSocketTextListener() {
            @Override
            public void onMessage(String message) {
                response.set(message);
                l.countDown();
            }

            @Override
            public void onOpen(WebSocket websocket) {
            }

            @Override
            public void onClose(WebSocket websocket) {
            }

            @Override
            public void onError(Throwable t) {
            }
        });

        l.await(5, TimeUnit.SECONDS);

        webSocket.close();
        assertEquals(response.get(), "Hello World from Nettosphere");
    } finally {
        c.close();
    }
}

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

License:Open Source License

/**
 * Starts the Server with the specified {@link Connection} settings.
 * //w ww . j  a v  a  2s. c  o  m
 * @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();

}

From source file:org.caffinitas.prometheusmetrics.PrometheusMetricsExporter.java

License:Apache License

private void setupNetty() throws CertificateException, SSLException {
    final SslContext sslCtx;
    if (config.ssl) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        LOGGER.info("Setting up SSL context for certificate subject DN {} valid until {}",
                ssc.cert().getSubjectDN(), ssc.cert().getNotAfter());
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {/*from   ww w .j a  va  2 s .c  o m*/
        sslCtx = null;
    }

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

    this.nettyChannel = new ServerBootstrap().option(ChannelOption.SO_BACKLOG, 1024)
            .group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ServerInitializer(sslCtx)).bind(config.bindAddress, config.httpPort)
            .syncUninterruptibly().channel();

    nettyChannel.closeFuture().addListener(f -> {
        LOGGER.info("Shutting down listener");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    });
}

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

License:Open Source License

@Provides
@Singleton/*from w w w .  j  a  va  2s . c  om*/
static Optional<SelfSignedCertificate> selfSignedCertificate(ServerConfig serverConfig) {
    if (!serverConfig.isGenerateSelfSignedCertificate()) {
        return Optional.empty();
    }
    logger.warn("Generating self-signed certificate. This should only happen on local!!!");
    try {
        return Optional.of(new SelfSignedCertificate());
    } catch (CertificateException e) {
        // Can't happen.
        throw new IllegalStateException(e);
    }
}

From source file:org.ftccommunity.services.DevConsole.java

License:Apache License

/**
 * Start the service./*from  w ww.j a v  a 2 s  . c o m*/
 */
@Override
protected void startUp() throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new TelnetServerInitializer(sslCtx));
    mainThread = Thread.currentThread();
}

From source file:org.jocean.http.server.HttpTestServer.java

License:Apache License

public HttpTestServer(final boolean enableSSL, final SocketAddress localAddress, final EventLoopGroup bossGroup,
        final EventLoopGroup workerGroup, final Class<? extends ServerChannel> serverChannelType,
        final Callable<ChannelInboundHandler> newHandler) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (enableSSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {//w w  w  .j  a  va 2s  . com
        sslCtx = null;
    }

    // Configure the server.
    _bossGroup = bossGroup;
    _workerGroup = workerGroup;

    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_BACKLOG, 1024);
    b.group(_bossGroup, _workerGroup).channel(serverChannelType).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new HttpTestServerInitializer(sslCtx, newHandler));

    b.bind(localAddress).sync();
}