io.netty.handler.ssl.SslHandler Java Examples

The following examples show how to use io.netty.handler.ssl.SslHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SslBindClientHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private void onSslHandshakeComplete(Future<? super Channel> result, SslHandler handler) {
   try {
      if(!result.isSuccess()) {
         if (logger.isDebugEnabled()) {
            Throwable cause = result.cause();
            if (!(cause instanceof ClosedChannelException)) {
               logger.debug("SSL handshake failed: {}", (cause == null) ? "unknown" : cause.getMessage(), cause);
            }
         }
         return;
      }

      String clientName = extractClientName(handler);
      if(clientName != null) {
         Channel channel = (Channel) result.get();
         Client.bind(channel, registry.load(clientName));
      }
   }
   catch(Exception e) {
      logger.debug("Unable to determine client auth", e);
   }
}
 
Example #2
Source File: Http1TunnelConnectionPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void sslContextProvided_andProxyUsingHttps_addsSslHandler() {
    SslHandler mockSslHandler = mock(SslHandler.class);
    TestSslContext mockSslCtx = new TestSslContext(mockSslHandler);

    Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, remoteAddr, initFuture) -> {
        initFuture.setSuccess(mockChannel);
        return mock(ChannelHandler.class);
    };

    Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, mockSslCtx,
            HTTPS_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, supplier);

    tunnelPool.acquire().awaitUninterruptibly();

    ArgumentCaptor<ChannelHandler> handlersCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
    verify(mockPipeline, times(2)).addLast(handlersCaptor.capture());

    assertThat(handlersCaptor.getAllValues().get(0)).isEqualTo(mockSslHandler);
}
 
Example #3
Source File: ProtocolNegotiators.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
public Handler newHandler(GrpcHttp2ConnectionHandler handler) {
  final HostPort hostPort = parseAuthority(handler.getAuthority());

  ChannelHandler sslBootstrap = new ChannelHandlerAdapter() {
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
      SSLEngine sslEngine = sslContext.newEngine(ctx.alloc(), hostPort.host, hostPort.port);
      SSLParameters sslParams = sslEngine.getSSLParameters();
      sslParams.setEndpointIdentificationAlgorithm("HTTPS");
      sslEngine.setSSLParameters(sslParams);
      ctx.pipeline().replace(this, null, new SslHandler(sslEngine, false));
    }
  };
  return new BufferUntilTlsNegotiatedHandler(sslBootstrap, handler);
}
 
Example #4
Source File: ProxyConnection.java    From yfs with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypts traffic on this connection with SSL/TLS.
 * 
 * @param pipeline
 *            the ChannelPipeline on which to enable encryption
 * @param sslEngine
 *            the {@link SSLEngine} for doing the encryption
 * @param authenticateClients
 *            determines whether to authenticate clients or not
 * @return a Future for when the SSL handshake has completed
 */
protected Future<Channel> encrypt(ChannelPipeline pipeline,
                                  SSLEngine sslEngine,
                                  boolean authenticateClients) {
    LOG.debug("Enabling encryption with SSLEngine: {}",
            sslEngine);
    this.sslEngine = sslEngine;
    sslEngine.setUseClientMode(runsAsSslClient);
    sslEngine.setNeedClientAuth(authenticateClients);
    if (null != channel) {
        channel.config().setAutoRead(true);
    }
    SslHandler handler = new SslHandler(sslEngine);
    if(pipeline.get("ssl") == null) {
        pipeline.addFirst("ssl", handler);
    } else {
        // The second SSL handler is added to handle the case
        // where the proxy (running as MITM) has to chain with
        // another SSL enabled proxy. The second SSL handler
        // is to perform SSL with the server.
        pipeline.addAfter("ssl", "sslWithServer", handler);
    }
    return handler.handshakeFuture();
}
 
Example #5
Source File: SecureChatServerHandler.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // 一旦session处于安全状态, 发送一个标记将但前channel注册到全局channel列表
    // 可以接收其他channel的消息.
    ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
            new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush(
                            "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n");
                    ctx.writeAndFlush(
                            "Your session is protected by " +
                                    ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() +
                                    " cipher suite.\n");

                    channels.add(ctx.channel());
                }
    });
}
 
Example #6
Source File: UserClient.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override protected void setupSSL(ChannelPipeline pipe,
    ConnectionMultiListener.SSLHandshakeListener sslHandshakeListener) {

  String peerHost = endpoint.getAddress();
  int peerPort = endpoint.getUserPort();
  SSLEngine sslEngine = sslConfig.createSSLEngine(allocator, peerHost, peerPort);

  // Add SSL handler into pipeline
  SslHandler sslHandler = new SslHandler(sslEngine);
  sslHandler.setHandshakeTimeoutMillis(sslConfig.getHandshakeTimeout());

  // Add a listener for SSL Handshake complete. The Drill client handshake will be enabled only
  // after this is done.
  sslHandler.handshakeFuture().addListener(sslHandshakeListener);
  pipe.addFirst(RpcConstants.SSL_HANDLER, sslHandler);
  logger.debug(sslConfig.toString());
}
 
Example #7
Source File: NettyHttpServletRequest.java    From cxf with Apache License 2.0 6 votes vote down vote up
public NettyHttpServletRequest(HttpRequest request, String contextPath, ChannelHandlerContext ctx) {
    this.originalRequest = request;
    this.contextPath = contextPath;
    this.uriParser = new URIParser(contextPath);
    uriParser.parse(request.uri());
    this.inputStream = new NettyServletInputStream((HttpContent)request);
    this.reader = new BufferedReader(new InputStreamReader(inputStream));
    this.queryStringDecoder = new QueryStringDecoder(request.uri());
    // setup the SSL security attributes
    this.channelHandlerContext = ctx;
    SslHandler sslHandler = channelHandlerContext.pipeline().get(SslHandler.class);
    if (sslHandler != null) {
        SSLSession session = sslHandler.engine().getSession();
        if (session != null) {
            attributes.put(SSL_CIPHER_SUITE_ATTRIBUTE, session.getCipherSuite());
            try {
                attributes.put(SSL_PEER_CERT_CHAIN_ATTRIBUTE, session.getPeerCertificates());
            } catch (SSLPeerUnverifiedException ex) {
                // do nothing here
            }
        }
    }
}
 
Example #8
Source File: ProtocolNegotiatorsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void tlsHandler_userEventTriggeredSslEvent_supportedProtocolGrpcExp() throws Exception {
  SslHandler goodSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "grpc-exp";
    }
  };

  ChannelHandler handler = new ServerTlsHandler(sslContext, grpcHandler);
  pipeline.addLast(handler);

  pipeline.replace(SslHandler.class, null, goodSslHandler);
  channelHandlerCtx = pipeline.context(handler);
  Object sslEvent = SslHandshakeCompletionEvent.SUCCESS;

  pipeline.fireUserEventTriggered(sslEvent);

  assertTrue(channel.isOpen());
  ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
  assertNotNull(grpcHandlerCtx);
}
 
Example #9
Source File: OcspTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static ChannelHandler newServerHandler(final SslContext context,
        final byte[] response, final ChannelHandler handler) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            SslHandler sslHandler = context.newHandler(ch.alloc());

            if (response != null) {
                ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
                engine.setOcspResponse(response);
            }

            pipeline.addLast(sslHandler);

            if (handler != null) {
                pipeline.addLast(handler);
            }
        }
    };
}
 
Example #10
Source File: Http1MutualSslChannelInitializer.java    From zuul with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception
{
    SslHandler sslHandler = sslContext.newHandler(ch.alloc());
    sslHandler.engine().setEnabledProtocols(sslContextFactory.getProtocols());

    // Configure our pipeline of ChannelHandlerS.
    ChannelPipeline pipeline = ch.pipeline();

    storeChannel(ch);
    addTimeoutHandlers(pipeline);
    addPassportHandler(pipeline);
    addTcpRelatedHandlers(pipeline);
    pipeline.addLast("ssl", sslHandler);
    addSslInfoHandlers(pipeline, isSSlFromIntermediary);
    addSslClientCertChecks(pipeline);
    addHttp1Handlers(pipeline);
    addHttpRelatedHandlers(pipeline);
    addZuulHandlers(pipeline);
}
 
Example #11
Source File: OcspServerExample.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static ChannelInitializer<Channel> newServerHandler(final ReferenceCountedOpenSslContext context,
        final OCSPResp response) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            SslHandler sslHandler = context.newHandler(ch.alloc());

            if (response != null) {
                ReferenceCountedOpenSslEngine engine
                    = (ReferenceCountedOpenSslEngine) sslHandler.engine();

                engine.setOcspResponse(response.getEncoded());
            }

            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(sslHandler);

            // so on and so forth...
        }
    };
}
 
Example #12
Source File: Ipcd10ChannelInitializer.java    From arcusipcd with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
	
	ChannelPipeline pipeline = ch.pipeline();
	
	if (serverTlsContext != null && serverTlsContext.useTls()) {
		SSLEngine engine = serverTlsContext.getContext().createSSLEngine();
		engine.setUseClientMode(false);
		pipeline.addLast("tls", new SslHandler(engine));
	}
	
	pipeline.addLast("encoder", new HttpResponseEncoder());
       pipeline.addLast("decoder", new HttpRequestDecoder());
       pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
       pipeline.addLast("handler", new Ipcd10WebSocketServerHandler(false));
}
 
Example #13
Source File: NettyServer.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Override
public void channelActive(final ChannelHandlerContext ctx) {
    LOG.info("NettyServerHandler -> New active channel: {}", ctx.channel());
    SslHandler handler = ctx.pipeline().get(SslHandler.class);
    if (handler != null) {
        handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
            @Override
            public void operationComplete(Future<Channel> future) throws Exception {
                LOG.info("Server -> SSL handshake completed. Succeeded: {}", future.isSuccess());
                if (!future.isSuccess()) {
                    ctx.close();
                }
            }
        });
    }

    channelActiveCount.incrementAndGet();
}
 
Example #14
Source File: HttpClientConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) {
	SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
	if (sslHandler == null) {
		throw new IllegalStateException("Cannot determine negotiated application-level protocol.");
	}
	String protocol = sslHandler.applicationProtocol() != null ? sslHandler.applicationProtocol() : ApplicationProtocolNames.HTTP_1_1;
	if (log.isDebugEnabled()) {
		log.debug(format(ctx.channel(), "Negotiated application-level protocol [" + protocol + "]"));
	}
	if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
		configureHttp2Pipeline(ctx.channel().pipeline(), decoder, http2Settings, observer);
	}
	else if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
		configureHttp11Pipeline(ctx.channel().pipeline(), acceptGzip, decoder, metricsRecorder, uriTagValue);
	}
	else {
		throw new IllegalStateException("unknown protocol: " + protocol);
	}

	ctx.fireChannelActive();

	ctx.channel().pipeline().remove(this);
}
 
Example #15
Source File: NettyAcceptor.java    From cloud-pubsub-mqtt-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the the various transport protocols for this server,
 * and setup their handlers/callbacks.
 */
@Override
public void initialize(IMessaging messaging, Properties props) throws IOException {
  bossGroup = new NioEventLoopGroup();
  workerGroup = new NioEventLoopGroup();

  initializePlainTcpTransport(messaging, props);
  initializeWebSocketTransport(messaging, props);
  String sslTcpPortProp = props.getProperty(Constants.SSL_PORT_PROPERTY_NAME);
  String wssPortProp = props.getProperty(Constants.WSS_PORT_PROPERTY_NAME);
  if (sslTcpPortProp != null || wssPortProp != null) {
    SslHandler sslHandler = initSslHandler(props);
    if (sslHandler == null) {
      LOG.error("Can't initialize SSLHandler layer! Exiting, check your configuration of jks");
      return;
    }
    initializeSslTcpTransport(messaging, props, sslHandler);
    initializeWssTransport(messaging, props, sslHandler);
  }
  // initialize ProxyContext and Pubsub impl
  context.open();
  pubsub.initialize(context);
}
 
Example #16
Source File: NettyHttpClientPipelineFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    SslHandler sslHandler = configureClientSSLOnDemand();
    if (sslHandler != null) {
        LOG.log(Level.FINE,
                "Server SSL handler configured and added as an interceptor against the ChannelPipeline: {}",
                sslHandler);
        pipeline.addLast("ssl", sslHandler);
    }


    pipeline.addLast("decoder", new HttpResponseDecoder());
    // TODO need to configure the aggregator size
    pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
    pipeline.addLast("encoder", new HttpRequestEncoder());
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
    if (readTimeout > 0) {
        pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS));
    }
    pipeline.addLast("client", new NettyHttpClientHandler());
}
 
Example #17
Source File: NettyHttpServletPipelineFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected ChannelPipeline getDefaulHttpChannelPipeline(Channel channel) throws Exception {

        // Create a default pipeline implementation.
        ChannelPipeline pipeline = channel.pipeline();

        SslHandler sslHandler = configureServerSSLOnDemand();
        if (sslHandler != null) {
            LOG.log(Level.FINE,
                    "Server SSL handler configured and added as an interceptor against the ChannelPipeline: {}",
                    sslHandler);
            pipeline.addLast("ssl", sslHandler);
        }

        pipeline.addLast("decoder", new HttpRequestDecoder());
        pipeline.addLast("encoder", new HttpResponseEncoder());
        pipeline.addLast("aggregator", new HttpObjectAggregator(maxChunkContentSize));
        
        // Remove the following line if you don't want automatic content
        // compression.
        pipeline.addLast("deflater", new HttpContentCompressor());
        // Set up the idle handler
        pipeline.addLast("idle", new IdleStateHandler(nettyHttpServerEngine.getReadIdleTime(),
                nettyHttpServerEngine.getWriteIdleTime(), 0));

        return pipeline;
    }
 
Example #18
Source File: MqttTransportServerInitializer.java    From Groza with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();//设置ChannelPipeLine
    SslHandler sslHandler = null;
    //判断SSL处理器处理类是否为空,如果不为空,将SSL处理器加入到ChannelPipeLine
    if (sslHandlerProvider != null) {
        sslHandler = sslHandlerProvider.getSslHandler();
        pipeline.addLast(sslHandler);
    }
    //添加负载内容的解编码器
    pipeline.addLast("decoder", new MqttDecoder(maxPayloadSize));
    pipeline.addLast("encoder", MqttEncoder.INSTANCE);

    MqttTransportHandler handler = new MqttTransportHandler(processor, deviceService, authService, relationService,
            adaptor, sslHandler, quotaService);

    //添加Mqtt协议处理器
    pipeline.addLast(handler);
    //异步操作完成时回调
    ch.closeFuture().addListener(handler);
}
 
Example #19
Source File: MutualAuthHandler.java    From xio with Apache License 2.0 6 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
  if (evt instanceof SslHandshakeCompletionEvent) {
    ctx.pipeline().remove(this);

    SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
    String peerIdentity = TlsAuthState.UNAUTHENTICATED;
    if (handshakeEvent.isSuccess()) {
      SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
      if (sslHandler == null) {
        throw new IllegalStateException(
            "cannot find a SslHandler in the pipeline (required for MutualAuthHandler)");
      }
      peerIdentity = getPeerIdentity(sslHandler.engine());
    }
    TlsAuthState.setPeerIdentity(ctx, peerIdentity);
    peerIdentityEstablished(ctx, peerIdentity);
  }

  ctx.fireUserEventTriggered(evt);
}
 
Example #20
Source File: ServiceChannelInitializer.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    if (sslCtxRefresher != null && this.enableTls) {
        if (this.tlsEnabledWithKeyStore) {
            ch.pipeline().addLast(TLS_HANDLER,
                    new SslHandler(nettySSLContextAutoRefreshBuilder.get().createSSLEngine()));
        } else{
            SslContext sslContext = sslCtxRefresher.get();
            if (sslContext != null) {
                ch.pipeline().addLast(TLS_HANDLER, sslContext.newHandler(ch.alloc()));
            }
        }
    }
    ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(
        Commands.DEFAULT_MAX_MESSAGE_SIZE + Commands.MESSAGE_SIZE_FRAME_PADDING, 0, 4, 0, 4));
    ch.pipeline().addLast("handler", new ServerConnection(discoveryService));
}
 
Example #21
Source File: SslParameterHandler.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Override
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {

    if (!(evt instanceof SslHandshakeCompletionEvent)) {
        super.userEventTriggered(ctx, evt);
        return;
    }

    final Channel channel = ctx.channel();
    final SslHandler sslHandler = (SslHandler) channel.pipeline().get(ChannelHandlerNames.SSL_HANDLER);
    final SSLSession session = sslHandler.engine().getSession();
    channel.attr(ChannelAttributes.AUTH_CIPHER_SUITE).set(session.getCipherSuite());
    channel.attr(ChannelAttributes.AUTH_PROTOCOL).set(session.getProtocol());

    channel.pipeline().remove(this);

    super.userEventTriggered(ctx, evt);
}
 
Example #22
Source File: NettyTcpTransport.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext context) throws Exception {
   // In the Secure case we need to let the handshake complete before we
   // trigger the connected event.
   if (!isSSL()) {
      handleConnected(context.channel());
   } else {
      SslHandler sslHandler = context.pipeline().get(SslHandler.class);
      sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
         @Override
         public void operationComplete(Future<Channel> future) throws Exception {
            if (future.isSuccess()) {
               LOG.trace("SSL Handshake has completed: {}", channel);
               handleConnected(channel);
            } else {
               LOG.trace("SSL Handshake has failed: {}", channel);
               handleException(channel, future.cause());
            }
         }
      });
   }
}
 
Example #23
Source File: HttpRequestInitializer.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
   ChannelPipeline pipeline = ch.pipeline();
   pipeline.addLast(inboundIpTracking);

   if (serverTlsContext != null && serverTlsContext.useTls()) {
      SSLEngine engine = serverTlsContext.getContext().newEngine(ch.alloc());
      engine.setNeedClientAuth(serverConfig.isTlsNeedClientAuth());
      engine.setUseClientMode(false);
      pipeline.addLast(FILTER_SSL, new SslHandler(engine));
   }

   pipeline.addLast(FILTER_CODEC, new HttpServerCodec());
   pipeline.addLast(FILTER_HTTP_AGGREGATOR, new HttpObjectAggregator(65536));
   pipeline.addLast("bind-client-context", oauthBindClientContext);
   pipeline.addLast(FILTER_HANDLER, handlerProvider.get());
   pipeline.addLast(outboundIpTracking);
}
 
Example #24
Source File: TlsTcpChannelInitializer.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Override
protected void addSpecialHandlers(@NotNull final Channel ch) throws SslException {

    final int handshakeTimeout = tlsTcpListener.getTls().getHandshakeTimeout();
    final IdleStateHandler idleStateHandler = new IdleStateHandler(handshakeTimeout, 0, 0, TimeUnit.MILLISECONDS);
    final NoTlsHandshakeIdleHandler noTlsHandshakeIdleHandler = new NoTlsHandshakeIdleHandler(eventLog);
    if (handshakeTimeout > 0) {
        ch.pipeline().addLast(NEW_CONNECTION_IDLE_HANDLER, idleStateHandler);
        ch.pipeline().addLast(NO_TLS_HANDSHAKE_IDLE_EVENT_HANDLER, noTlsHandshakeIdleHandler);
    }

    final Tls tls = tlsTcpListener.getTls();
    final SslHandler sslHandler = sslFactory.getSslHandler(ch, tls);
    sslHandler.handshakeFuture().addListener(future -> {
        if (handshakeTimeout > 0) {
            ch.pipeline().remove(idleStateHandler);
            ch.pipeline().remove(noTlsHandshakeIdleHandler);
        }
        addNoConnectIdleHandlerAfterTlsHandshake(ch);
    });

    new SslInitializer(sslHandler, tls, eventLog, sslParameterHandler).addHandlers(ch);
}
 
Example #25
Source File: NettyClient.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Create a NettyClient.
 * @param hostname the host to connect to.
 * @param port the port to connect to.
 * @param sslFactory the {@link SSLFactory} to use if SSL is enabled.
 */
public NettyClient(final String hostname, final int port, final SSLFactory sslFactory) throws InterruptedException {
  this.hostname = hostname;
  this.port = port;
  b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
      ChannelPipeline pipeline = ch.pipeline();
      if (sslFactory != null) {
        pipeline.addLast("sslHandler",
            new SslHandler(sslFactory.createSSLEngine(hostname, port, SSLFactory.Mode.CLIENT)));
      }
      pipeline.addLast(new HttpClientCodec()).addLast(new ChunkedWriteHandler()).addLast(communicationHandler);
    }
  });
  createChannel();
}
 
Example #26
Source File: SslSimpleBuilder.java    From jlogstash-input-plugin with Apache License 2.0 6 votes vote down vote up
public SslHandler build(ByteBufAllocator bufferAllocator) throws SSLException {
    SslContextBuilder builder = SslContextBuilder.forServer(sslCertificateFile, sslKeyFile, passPhrase);

    builder.ciphers(Arrays.asList(ciphers));

    if(requireClientAuth()) {
        logger.debug("Certificate Authorities: " + certificateAuthorities);
        builder.trustManager(new File(certificateAuthorities));
    }

    SslContext context = builder.build();
    SslHandler sslHandler = context.newHandler(bufferAllocator);

    SSLEngine engine = sslHandler.engine();
    engine.setEnabledProtocols(protocols);


    if(requireClientAuth()) {
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(true);
    }

    return sslHandler;
}
 
Example #27
Source File: PublicAccessLogHandlerTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link EmbeddedChannel} that incorporates an instance of {@link PublicAccessLogHandler}
 * and {@link EchoMethodHandler}.
 * @param useSSL {@code true} to add an {@link SslHandler} to the pipeline.
 * @return an {@link EmbeddedChannel} that incorporates an instance of {@link PublicAccessLogHandler}
 *         and {@link EchoMethodHandler}, and an {@link SslHandler} if needed.
 */
private EmbeddedChannel createChannel(boolean useSSL) {
  EmbeddedChannel channel = new EmbeddedChannel();
  if (useSSL) {
    SSLEngine sslEngine = SSL_CONTEXT.newEngine(channel.alloc());
    // HttpRequests pass through the SslHandler without a handshake (it only operates on ByteBuffers) so we have
    // to mock certain methods of SSLEngine and SSLSession to ensure that we can test certificate logging.
    SSLEngine mockSSLEngine =
        new MockSSLEngine(sslEngine, new MockSSLSession(sslEngine.getSession(), new Certificate[]{PEER_CERT}));
    channel.pipeline().addLast(new SslHandler(mockSSLEngine));
  }
  channel.pipeline()
      .addLast(new PublicAccessLogHandler(publicAccessLogger, new NettyMetrics(new MetricRegistry())))
      .addLast(new EchoMethodHandler());
  return channel;
}
 
Example #28
Source File: RntbdRequestManager.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
/**
 * Called once a close operation is made.
 *
 * @param context the {@link ChannelHandlerContext} for which the close operation is made
 * @param promise the {@link ChannelPromise} to notify once the operation completes
 */
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {

    this.traceOperation(context, "close");

    if (!this.closingExceptionally) {
        this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
    } else {
        logger.debug("{} closed exceptionally", context);
    }

    final SslHandler sslHandler = context.pipeline().get(SslHandler.class);

    if (sslHandler != null) {
        // Netty 4.1.36.Final: SslHandler.closeOutbound must be called before closing the pipeline
        // This ensures that all SSL engine and ByteBuf resources are released
        // This is something that does not occur in the call to ChannelPipeline.close that follows
        sslHandler.closeOutbound();
    }

    context.close(promise);
}
 
Example #29
Source File: SslFactoryTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_cert_auth_none() throws Exception {
    final File file = testKeyStoreGenerator.generateKeyStore("teststore", "JKS", "passwd1", "passwd2");
    final String keystorePath = file.getAbsolutePath();

    final Tls tls = new Tls.Builder()
            .withKeystorePath(keystorePath)
            .withKeystoreType("JKS")
            .withKeystorePassword("passwd1")
            .withPrivateKeyPassword("passwd2")
            .withProtocols(new ArrayList<>())
            .withTruststorePath(keystorePath)
            .withTruststoreType("JKS")
            .withTruststorePassword("passwd1")
            .withClientAuthMode(Tls.ClientAuthMode.NONE)
            .withCipherSuites(new ArrayList<>())
            .withHandshakeTimeout(10000)
            .build();

    final SslHandler sslHandler = sslFactory.getSslHandler(socketChannel, tls);

    assertFalse(sslHandler.engine().getNeedClientAuth());
    assertFalse(sslHandler.engine().getWantClientAuth());
}
 
Example #30
Source File: SslFactoryTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_cert_auth_required() throws Exception {
    final File file = testKeyStoreGenerator.generateKeyStore("teststore", "JKS", "passwd1", "passwd2");
    final String keystorePath = file.getAbsolutePath();


    final Tls tls = new Tls.Builder()
            .withKeystorePath(keystorePath)
            .withKeystoreType("JKS")
            .withKeystorePassword("passwd1")
            .withPrivateKeyPassword("passwd2")
            .withProtocols(new ArrayList<>())
            .withTruststorePath(keystorePath)
            .withTruststoreType("JKS")
            .withTruststorePassword("passwd1")
            .withClientAuthMode(Tls.ClientAuthMode.REQUIRED)
            .withCipherSuites(new ArrayList<>())
            .withHandshakeTimeout(10000)
            .build();


    final SslHandler sslHandler = sslFactory.getSslHandler(socketChannel, tls);

    assertTrue(sslHandler.engine().getNeedClientAuth());
    assertFalse(sslHandler.engine().getWantClientAuth());
}