List of usage examples for io.netty.handler.ssl SslHandler SslHandler
public SslHandler(SSLEngine engine)
From source file:org.eclipse.moquette.server.netty.NettyAcceptor.java
License:Open Source License
private void initializeSSLTCPTransport(IMessaging messaging, Properties props) throws IOException { String sslPortProp = props.getProperty(Constants.SSL_PORT_PROPERTY_NAME); if (sslPortProp == null) { //Do nothing no SSL configured LOG.info("SSL is disabled"); return;/*from www.ja v a2s .c om*/ } final String jksPath = props.getProperty(Constants.JKS_PATH_PROPERTY_NAME); if (jksPath == null || jksPath.isEmpty()) { //key_store_password or key_manager_password are empty LOG.warn("You have configured the SSL port but not the jks_path, SSL not started"); return; } //if we have the port also the jks then keyStorePassword and keyManagerPassword //has to be defined final String keyStorePassword = props.getProperty(Constants.KEY_STORE_PASSWORD_PROPERTY_NAME); final String keyManagerPassword = props.getProperty(Constants.KEY_MANAGER_PASSWORD_PROPERTY_NAME); if (keyStorePassword == null || keyStorePassword.isEmpty()) { //key_store_password or key_manager_password are empty LOG.warn("You have configured the SSL port but not the key_store_password, SSL not started"); return; } if (keyManagerPassword == null || keyManagerPassword.isEmpty()) { //key_manager_password or key_manager_password are empty LOG.warn("You have configured the SSL port but not the key_manager_password, SSL not started"); return; } int sslPort = Integer.parseInt(sslPortProp); String host = props.getProperty(Constants.HOST_PROPERTY_NAME); LOG.info("Starting SSL on port {} using keystore at {}", sslPort, jksPath); final NettyMQTTHandler handler = new NettyMQTTHandler(); handler.setMessaging(messaging); initFactory(host, sslPort, new PipelineInitializer() { @Override void init(ChannelPipeline pipeline) throws Exception { InputStream jksInputStream = jksDatastore(jksPath); SSLContext serverContext = SSLContext.getInstance("TLS"); final KeyStore ks = KeyStore.getInstance("JKS"); ks.load(jksInputStream, keyStorePassword.toCharArray()); final KeyManagerFactory kmf = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keyManagerPassword.toCharArray()); serverContext.init(kmf.getKeyManagers(), null, null); SSLEngine engine = serverContext.createSSLEngine(); engine.setUseClientMode(false); final SslHandler sslHandler = new SslHandler(engine); pipeline.addLast("ssl", sslHandler); //pipeline.addFirst("metrics", new BytesMetricsHandler(m_metricsCollector)); pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0, Constants.DEFAULT_CONNECT_TIMEOUT)); pipeline.addAfter("idleStateHandler", "idleEventHandler", new MoquetteIdleTimoutHandler()); //pipeline.addLast("logger", new LoggingHandler("Netty", LogLevel.ERROR)); pipeline.addLast("decoder", new MQTTDecoder()); pipeline.addLast("encoder", new MQTTEncoder()); pipeline.addLast("metrics", new MessageMetricsHandler(m_metricsCollector)); pipeline.addLast("handler", handler); } }); }
From source file:org.emsg.smart_connector.netty.acceptor.NettyAcceptor.java
License:Open Source License
private ChannelHandler createSslHandler(SSLContext sslContext) { SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(false);/* w w w.j av a 2 s. c o m*/ return new SslHandler(sslEngine); }
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// ww w . j a v a 2s .c om 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.graylog2.plugin.inputs.transports.util.KeyUtilTest.java
License:Open Source License
@Test public void testCreateNettySslHandler() throws Exception { if (exceptionClass != null) { expectedException.expect(exceptionClass); expectedException.expectMessage(exceptionMessage); }/*from w w w.j a va 2s . c o m*/ final File keyFile = resourceToFile(keyFileName); final File certFile = resourceToFile(CERTIFICATES.get(keyAlgorithm)); final KeyManager[] keyManagers = KeyUtil.initKeyStore(keyFile, certFile, keyPassword); final SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, new TrustManager[0], new SecureRandom()); assertThat(sslContext.getProtocol()).isEqualTo("TLS"); final SSLEngine sslEngine = sslContext.createSSLEngine(); assertThat(sslEngine.getEnabledCipherSuites()).isNotEmpty(); assertThat(sslEngine.getEnabledProtocols()).isNotEmpty(); final SslHandler sslHandler = new SslHandler(sslEngine); assertThat(sslHandler).isNotNull(); }
From source file:org.hornetq.core.remoting.impl.netty.NettyAcceptor.java
License:Apache License
public synchronized void start() throws Exception { if (channelClazz != null) { // Already started return;//w w w . j a v a 2s. c o m } if (useInvm) { channelClazz = LocalServerChannel.class; eventLoopGroup = new LocalEventLoopGroup(); } else { int threadsToUse; if (nioRemotingThreads == -1) { // Default to number of cores * 3 threadsToUse = Runtime.getRuntime().availableProcessors() * 3; } else { threadsToUse = this.nioRemotingThreads; } channelClazz = NioServerSocketChannel.class; eventLoopGroup = new NioEventLoopGroup(threadsToUse, new HornetQThreadFactory("hornetq-netty-threads", true, getThisClassLoader())); } bootstrap = new ServerBootstrap(); bootstrap.group(eventLoopGroup); bootstrap.channel(channelClazz); final SSLContext context; if (sslEnabled) { try { if (keyStorePath == null && TransportConstants.DEFAULT_TRUSTSTORE_PROVIDER.equals(keyStoreProvider)) throw new IllegalArgumentException("If \"" + TransportConstants.SSL_ENABLED_PROP_NAME + "\" is true then \"" + TransportConstants.KEYSTORE_PATH_PROP_NAME + "\" must be non-null " + "unless an alternative \"" + TransportConstants.KEYSTORE_PROVIDER_PROP_NAME + "\" has been specified."); context = SSLSupport.createContext(keyStoreProvider, keyStorePath, keyStorePassword, trustStoreProvider, trustStorePath, trustStorePassword); } catch (Exception e) { IllegalStateException ise = new IllegalStateException( "Unable to create NettyAcceptor for " + host + ":" + port); ise.initCause(e); throw ise; } } else { context = null; // Unused } ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() { @Override public void initChannel(Channel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); if (sslEnabled) { SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(false); if (needClientAuth) engine.setNeedClientAuth(true); // setting the enabled cipher suites resets the enabled protocols so we need // to save the enabled protocols so that after the customer cipher suite is enabled // we can reset the enabled protocols if a customer protocol isn't specified String[] originalProtocols = engine.getEnabledProtocols(); if (enabledCipherSuites != null) { try { engine.setEnabledCipherSuites( SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites)); } catch (IllegalArgumentException e) { HornetQServerLogger.LOGGER.invalidCipherSuite(SSLSupport .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites())); throw e; } } if (enabledProtocols != null) { try { engine.setEnabledProtocols( SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols)); } catch (IllegalArgumentException e) { HornetQServerLogger.LOGGER.invalidProtocol( SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols())); throw e; } } else { engine.setEnabledProtocols(originalProtocols); } SslHandler handler = new SslHandler(engine); pipeline.addLast("ssl", handler); } pipeline.addLast(protocolHandler.getProtocolDecoder()); } }; bootstrap.childHandler(factory); // Bind bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay); if (tcpReceiveBufferSize != -1) { bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize); } if (tcpSendBufferSize != -1) { bootstrap.childOption(ChannelOption.SO_SNDBUF, tcpSendBufferSize); } if (backlog != -1) { bootstrap.option(ChannelOption.SO_BACKLOG, backlog); } bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.childOption(ChannelOption.SO_REUSEADDR, true); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE); channelGroup = new DefaultChannelGroup("hornetq-accepted-channels", GlobalEventExecutor.INSTANCE); serverChannelGroup = new DefaultChannelGroup("hornetq-acceptor-channels", GlobalEventExecutor.INSTANCE); if (httpUpgradeEnabled) { // the channel will be bound by the Web container and hand over after the HTTP Upgrade // handshake is successful } else { startServerChannels(); paused = false; if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(new SimpleString("factory"), new SimpleString(NettyAcceptorFactory.class.getName())); props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host)); props.putIntProperty(new SimpleString("port"), port); Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props); notificationService.sendNotification(notification); } if (batchDelay > 0) { flusher = new BatchFlusher(); batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS); } // TODO: Think about add Version back to netty HornetQServerLogger.LOGGER.startedNettyAcceptor(TransportConstants.NETTY_VERSION, host, port); } }
From source file:org.hornetq.core.remoting.impl.netty.NettyConnector.java
License:Apache License
public synchronized void start() { if (channelClazz != null) { return;/*from w ww . j a v a 2s . c om*/ } int threadsToUse; if (nioRemotingThreads == -1) { // Default to number of cores * 3 threadsToUse = Runtime.getRuntime().availableProcessors() * 3; } else { threadsToUse = this.nioRemotingThreads; } if (useNioGlobalWorkerPool) { channelClazz = NioSocketChannel.class; group = SharedNioEventLoopGroup.getInstance(threadsToUse); } else { channelClazz = NioSocketChannel.class; group = new NioEventLoopGroup(threadsToUse); } // if we are a servlet wrap the socketChannelFactory if (useServlet) { // TODO: This will be replaced by allow upgrade HTTP connection from Undertow.; } bootstrap = new Bootstrap(); bootstrap.channel(channelClazz); bootstrap.group(group); bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay); if (connectTimeoutMillis != -1) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis); } if (tcpReceiveBufferSize != -1) { bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize); } if (tcpSendBufferSize != -1) { bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize); } bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.ALLOCATOR, new UnpooledByteBufAllocator(false)); channelGroup = new DefaultChannelGroup("hornetq-connector", GlobalEventExecutor.INSTANCE); final SSLContext context; if (sslEnabled) { try { // HORNETQ-680 - override the server-side config if client-side system properties are set String realKeyStorePath = keyStorePath; String realKeyStoreProvider = keyStoreProvider; String realKeyStorePassword = keyStorePassword; if (System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME) != null) { realKeyStorePath = System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME); } if (System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME) != null) { realKeyStorePassword = System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME); } if (System.getProperty(HORNETQ_KEYSTORE_PROVIDER_PROP_NAME) != null) { realKeyStoreProvider = System.getProperty(HORNETQ_KEYSTORE_PROVIDER_PROP_NAME); } if (System.getProperty(HORNETQ_KEYSTORE_PATH_PROP_NAME) != null) { realKeyStorePath = System.getProperty(HORNETQ_KEYSTORE_PATH_PROP_NAME); } if (System.getProperty(HORNETQ_KEYSTORE_PASSWORD_PROP_NAME) != null) { realKeyStorePassword = System.getProperty(HORNETQ_KEYSTORE_PASSWORD_PROP_NAME); } String realTrustStorePath = trustStorePath; String realTrustStoreProvider = trustStoreProvider; String realTrustStorePassword = trustStorePassword; if (System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME) != null) { realTrustStorePath = System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME); } if (System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME) != null) { realTrustStorePassword = System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME); } if (System.getProperty(HORNETQ_TRUSTSTORE_PROVIDER_PROP_NAME) != null) { realTrustStoreProvider = System.getProperty(HORNETQ_TRUSTSTORE_PROVIDER_PROP_NAME); } if (System.getProperty(HORNETQ_TRUSTSTORE_PATH_PROP_NAME) != null) { realTrustStorePath = System.getProperty(HORNETQ_TRUSTSTORE_PATH_PROP_NAME); } if (System.getProperty(HORNETQ_TRUSTSTORE_PASSWORD_PROP_NAME) != null) { realTrustStorePassword = System.getProperty(HORNETQ_TRUSTSTORE_PASSWORD_PROP_NAME); } context = SSLSupport.createContext(realKeyStoreProvider, realKeyStorePath, realKeyStorePassword, realTrustStoreProvider, realTrustStorePath, realTrustStorePassword); } catch (Exception e) { close(); IllegalStateException ise = new IllegalStateException( "Unable to create NettyConnector for " + host + ":" + port); ise.initCause(e); throw ise; } } else { context = null; // Unused } if (context != null && useServlet) { // TODO: Fix me //bootstrap.setOption("sslContext", context); } bootstrap.handler(new ChannelInitializer<Channel>() { public void initChannel(Channel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); if (sslEnabled && !useServlet) { SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(true); engine.setWantClientAuth(true); // setting the enabled cipher suites resets the enabled protocols so we need // to save the enabled protocols so that after the customer cipher suite is enabled // we can reset the enabled protocols if a customer protocol isn't specified String[] originalProtocols = engine.getEnabledProtocols(); if (enabledCipherSuites != null) { try { engine.setEnabledCipherSuites( SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites)); } catch (IllegalArgumentException e) { HornetQClientLogger.LOGGER.invalidCipherSuite(SSLSupport .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites())); throw e; } } if (enabledProtocols != null) { try { engine.setEnabledProtocols( SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols)); } catch (IllegalArgumentException e) { HornetQClientLogger.LOGGER.invalidProtocol( SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols())); throw e; } } else { engine.setEnabledProtocols(originalProtocols); } SslHandler handler = new SslHandler(engine); pipeline.addLast(handler); } if (httpEnabled) { pipeline.addLast(new HttpRequestEncoder()); pipeline.addLast(new HttpResponseDecoder()); pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE)); pipeline.addLast(new HttpHandler()); } if (httpUpgradeEnabled) { // prepare to handle a HTTP 101 response to upgrade the protocol. final HttpClientCodec httpClientCodec = new HttpClientCodec(); pipeline.addLast(httpClientCodec); pipeline.addLast("http-upgrade", new HttpUpgradeHandler(pipeline, httpClientCodec)); } pipeline.addLast(new HornetQFrameDecoder2()); pipeline.addLast(new HornetQClientChannelHandler(channelGroup, handler, new Listener())); } }); if (batchDelay > 0) { flusher = new BatchFlusher(); batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS); } HornetQClientLogger.LOGGER.debug("Started Netty Connector version " + TransportConstants.NETTY_VERSION); }
From source file:org.jboss.aerogear.simplepush.server.netty.SockJSChannelInitializer.java
License:Apache License
@Override protected void initChannel(final SocketChannel socketChannel) throws Exception { final ChannelPipeline pipeline = socketChannel.pipeline(); if (sockjsConfig.isTls()) { final SSLEngine engine = sslContext.createSSLEngine(); engine.setUseClientMode(false);/*from w w w. jav a 2 s .c o m*/ pipeline.addLast(new SslHandler(engine)); } pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); final DefaultSimplePushServer simplePushServer = new DefaultSimplePushServer(datastore, simplePushConfig, privateKey); pipeline.addLast(new NotificationHandler(simplePushServer)); pipeline.addLast(new CorsInboundHandler()); pipeline.addLast(new SockJsHandler(new SimplePushServiceFactory(sockjsConfig, simplePushServer))); pipeline.addLast(backgroundGroup, new UserAgentReaperHandler(simplePushServer)); pipeline.addLast(new CorsOutboundHandler()); }
From source file:org.onosproject.openflow.controller.impl.OFChannelInitializer.java
License:Apache License
@Override protected void initChannel(SocketChannel ch) throws Exception { OFChannelHandler handler = new OFChannelHandler(controller); ChannelPipeline pipeline = ch.pipeline(); if (sslContext != null) { log.info("OpenFlow SSL enabled."); SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setNeedClientAuth(true); sslEngine.setUseClientMode(false); sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols()); sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites()); sslEngine.setEnableSessionCreation(true); SslHandler sslHandler = new SslHandler(sslEngine); pipeline.addLast("ssl", sslHandler); } else {//from w w w . j av a 2 s. c o m log.debug("OpenFlow SSL disabled."); } pipeline.addLast("ofmessageencoder", OFMessageEncoder.getInstance()); pipeline.addLast("ofmessagedecoder", OFMessageDecoder.getInstance()); pipeline.addLast("idle", new IdleStateHandler(20, 25, 0)); pipeline.addLast("timeout", new ReadTimeoutHandler(30)); // XXX S ONOS: was 15 increased it to fix Issue #296 pipeline.addLast("handshaketimeout", new HandshakeTimeoutHandler(handler, 60)); // ExecutionHandler equivalent now part of Netty core if (pipelineExecutor != null) { pipeline.addLast(pipelineExecutor, "handler", handler); } else { pipeline.addLast("handler", handler); } }
From source file:org.opendaylight.controller.netconf.util.AbstractSslChannelInitializer.java
License:Open Source License
private void initSsl(SocketChannel ch) { SSLEngine sslEngine = maybeContext.get().createSSLEngine(); initSslEngine(sslEngine);/*from ww w .j a v a 2 s .co m*/ final SslHandler handler = new SslHandler(sslEngine); ch.pipeline().addLast("ssl", handler); }
From source file:org.opendaylight.ocpjava.protocol.impl.clients.SimpleClientInitializer.java
License:Open Source License
@Override public void initChannel(NioSocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (secured) { SSLEngine engine = ClientSslContextFactory.getClientContext().createSSLEngine(); engine.setUseClientMode(true);//from w ww. j av a 2 s . c o m pipeline.addLast("ssl", new SslHandler(engine)); } SimpleClientHandler simpleClientHandler = new SimpleClientHandler(isOnlineFuture, scenarioHandler); simpleClientHandler.setScenario(scenarioHandler); pipeline.addLast("framer", new SimpleClientFramer()); pipeline.addLast("handler", simpleClientHandler); isOnlineFuture = null; }