io.netty.handler.ssl.SslHandshakeCompletionEvent Java Examples

The following examples show how to use io.netty.handler.ssl.SslHandshakeCompletionEvent. 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: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void tlsHandler_userEventTriggeredSslEvent_supportedProtocolH2() throws Exception {
  SslHandler goodSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "h2";
    }
  };

  ChannelHandler handler = new ServerTlsHandler(grpcHandler, sslContext, null);
  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 #2
Source File: NettyPipelineSslUtils.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the {@link SSLSession} from the {@link ChannelPipeline} if the {@link SslHandshakeCompletionEvent}
 * is successful.
 *
 * @param pipeline the {@link ChannelPipeline} which contains handler containing the {@link SSLSession}.
 * @param sslEvent the event indicating a SSL/TLS handshake completed.
 * @param failureConsumer invoked if a failure is encountered.
 * @return The {@link SSLSession} or {@code null} if none can be found.
 */
@Nullable
public static SSLSession extractSslSession(ChannelPipeline pipeline,
                                           SslHandshakeCompletionEvent sslEvent,
                                           Consumer<Throwable> failureConsumer) {
    if (sslEvent.isSuccess()) {
        final SslHandler sslHandler = pipeline.get(SslHandler.class);
        if (sslHandler != null) {
            return sslHandler.engine().getSession();
        } else {
            failureConsumer.accept(new IllegalStateException("Unable to find " + SslHandler.class.getName() +
                    " in the pipeline."));
        }
    } else {
        failureConsumer.accept(sslEvent.cause());
    }
    return null;
}
 
Example #3
Source File: DefaultNettyConnection.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
    if (evt == CloseHandler.ProtocolPayloadEndEvent.OUTBOUND) {
        connection.channelOutboundListener.channelOutboundClosed();
    } else if (evt == ChannelOutputShutdownEvent.INSTANCE) {
        connection.closeHandler.channelClosedOutbound(ctx);
        connection.channelOutboundListener.channelClosed(StacklessClosedChannelException.newInstance(
                DefaultNettyConnection.class, "userEventTriggered(...)"));
    } else if (evt == ChannelInputShutdownReadComplete.INSTANCE) {
        // Notify close handler first to enhance error reporting
        connection.closeHandler.channelClosedInbound(ctx);
        // ChannelInputShutdownEvent is not always triggered and can get triggered before we tried to read
        // all the available data. ChannelInputShutdownReadComplete is the one that seems to (at least in
        // the current netty version) gets triggered reliably at the appropriate time.
        connection.nettyChannelPublisher.channelInboundClosed();
    } else if (evt instanceof SslHandshakeCompletionEvent) {
        connection.sslSession = extractSslSession(ctx.pipeline(), (SslHandshakeCompletionEvent) evt,
                this::tryFailSubscriber);
        if (subscriber != null) {
            assert waitForSslHandshake;
            completeSubscriber();
        }
    }
    ctx.fireUserEventTriggered(evt);
}
 
Example #4
Source File: RetryClient.java    From LittleProxy-mitm with Apache License 2.0 6 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
        throws Exception {
    LOG.info(">>> userEventTriggered " + evt);
    if (evt instanceof SslHandshakeCompletionEvent) {
        SslHandshakeCompletionEvent hce = (SslHandshakeCompletionEvent) evt;
        if (!hce.isSuccess()
                && hce.cause().getMessage().contains("unrecognized_name")) {
            LOG.info(">>> unrecognized_name");
            ctx.close();
            unrecognizedName = true;
            return;
        }
    }
    super.userEventTriggered(ctx, evt);
}
 
Example #5
Source File: RestartClient.java    From LittleProxy-mitm with Apache License 2.0 6 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
        throws Exception {
    LOG.info(">>> userEventTriggered " + evt);
    if (evt instanceof SslHandshakeCompletionEvent) {
        SslHandshakeCompletionEvent hce = (SslHandshakeCompletionEvent) evt;
        if (!hce.isSuccess()
                && hce.cause().getMessage()
                        .contains("unrecognized_name")) {
            LOG.info(">>> unrecognized_name");
            ctx.close();
            unrecognizedName = true;
            return;
        }
    }
    super.userEventTriggered(ctx, evt);
}
 
Example #6
Source File: SocketSslClientRenegotiateTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof SslHandshakeCompletionEvent) {
        SslHandshakeCompletionEvent handshakeEvt = (SslHandshakeCompletionEvent) evt;
        if (handshakeCounter == 0) {
            handshakeCounter++;
            if (handshakeEvt.cause() != null) {
                logger.warn("Handshake failed:", handshakeEvt.cause());
            }
            assertSame(SslHandshakeCompletionEvent.SUCCESS, evt);
        } else {
            if (ctx.channel().parent() == null) {
                assertTrue(handshakeEvt.cause() instanceof ClosedChannelException);
            }
        }
    }
}
 
Example #7
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 #8
Source File: SdsProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void clientSdsProtocolNegotiatorNewHandler_fireProtocolNegotiationEvent()
    throws IOException, InterruptedException {
  UpstreamTlsContext upstreamTlsContext =
      buildUpstreamTlsContextFromFilenames(CLIENT_KEY_FILE, CLIENT_PEM_FILE, CA_PEM_FILE);

  SdsProtocolNegotiators.ClientSdsHandler clientSdsHandler =
      new SdsProtocolNegotiators.ClientSdsHandler(grpcHandler, upstreamTlsContext);

  pipeline.addLast(clientSdsHandler);
  channelHandlerCtx = pipeline.context(clientSdsHandler);
  assertNotNull(channelHandlerCtx); // non-null since we just added it

  // kick off protocol negotiation.
  pipeline.fireUserEventTriggered(InternalProtocolNegotiationEvent.getDefault());
  channel.runPendingTasks(); // need this for tasks to execute on eventLoop
  channelHandlerCtx = pipeline.context(clientSdsHandler);
  assertThat(channelHandlerCtx).isNull();
  Object sslEvent = SslHandshakeCompletionEvent.SUCCESS;

  pipeline.fireUserEventTriggered(sslEvent);
  channel.runPendingTasks(); // need this for tasks to execute on eventLoop
  assertTrue(channel.isOpen());
}
 
Example #9
Source File: ProtocolNegotiators.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
  if (evt instanceof ProtocolNegotiationEvent) {
    pne = (ProtocolNegotiationEvent) evt;
  } else if (evt instanceof SslHandshakeCompletionEvent) {
    SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
    if (!handshakeEvent.isSuccess()) {
      logSslEngineDetails(Level.FINE, ctx, "TLS negotiation failed for new client.", null);
      ctx.fireExceptionCaught(handshakeEvent.cause());
      return;
    }
    SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
    if (!sslContext.applicationProtocolNegotiator().protocols().contains(
            sslHandler.applicationProtocol())) {
      logSslEngineDetails(Level.FINE, ctx, "TLS negotiation failed for new client.", null);
      ctx.fireExceptionCaught(unavailableException(
          "Failed protocol negotiation: Unable to find compatible protocol"));
      return;
    }
    ctx.pipeline().replace(ctx.name(), null, next);
    fireProtocolNegotiationEvent(ctx, sslHandler.engine().getSession());
  } else {
    super.userEventTriggered(ctx, evt);
  }
}
 
Example #10
Source File: ProtocolNegotiators.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected void userEventTriggered0(ChannelHandlerContext ctx, Object evt) throws Exception {
  if (evt instanceof SslHandshakeCompletionEvent) {
    SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
    if (handshakeEvent.isSuccess()) {
      SslHandler handler = ctx.pipeline().get(SslHandler.class);
      if (sslContext.applicationProtocolNegotiator().protocols()
          .contains(handler.applicationProtocol())) {
        // Successfully negotiated the protocol.
        logSslEngineDetails(Level.FINER, ctx, "TLS negotiation succeeded.", null);
        propagateTlsComplete(ctx, handler.engine().getSession());
      } else {
        Exception ex =
            unavailableException("Failed ALPN negotiation: Unable to find compatible protocol");
        logSslEngineDetails(Level.FINE, ctx, "TLS negotiation failed.", ex);
        ctx.fireExceptionCaught(ex);
      }
    } else {
      ctx.fireExceptionCaught(handshakeEvent.cause());
    }
  } else {
    super.userEventTriggered0(ctx, evt);
  }
}
 
Example #11
Source File: HttpServerHandler.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof SslHandshakeCompletionEvent) {
        final SslHandler sslHandler = ctx.channel().pipeline().get(SslHandler.class);
        sslSession = sslHandler != null ? sslHandler.engine().getSession() : null;
        return;
    }

    if (evt instanceof SslCloseCompletionEvent ||
        evt instanceof ChannelInputShutdownReadComplete) {
        // Expected events
        return;
    }

    logger.warn("{} Unexpected user event: {}", ctx.channel(), evt);
}
 
Example #12
Source File: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void tlsHandler_userEventTriggeredSslEvent_handshakeFailure() throws Exception {
  ChannelHandler handler = new ServerTlsHandler(grpcHandler, sslContext, null);
  pipeline.addLast(handler);
  channelHandlerCtx = pipeline.context(handler);
  Object sslEvent = new SslHandshakeCompletionEvent(new RuntimeException("bad"));

  final AtomicReference<Throwable> error = new AtomicReference<>();
  ChannelHandler errorCapture = new ChannelInboundHandlerAdapter() {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
      error.set(cause);
    }
  };

  pipeline.addLast(errorCapture);

  pipeline.fireUserEventTriggered(sslEvent);

  // No h2 protocol was specified, so there should be an error, (normally handled by WBAEH)
  assertThat(error.get()).hasMessageThat().contains("bad");
  ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
  assertNull(grpcHandlerCtx);
}
 
Example #13
Source File: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void clientTlsHandler_userEventTriggeredSslEvent_supportedProtocolH2() throws Exception {
  SslHandler goodSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "h2";
    }
  };
  DefaultEventLoopGroup elg = new DefaultEventLoopGroup(1);

  ClientTlsHandler handler = new ClientTlsHandler(grpcHandler, sslContext, "authority", elg);
  pipeline.addLast(handler);
  pipeline.replace(SslHandler.class, null, goodSslHandler);
  pipeline.fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT);
  channelHandlerCtx = pipeline.context(handler);
  Object sslEvent = SslHandshakeCompletionEvent.SUCCESS;

  pipeline.fireUserEventTriggered(sslEvent);

  ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
  assertNotNull(grpcHandlerCtx);
}
 
Example #14
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 #15
Source File: ProxyConnectConnectionFactoryFilterTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Test
public void noDeferSslHandler() {
    ChannelPipeline pipeline = configurePipeline(SslHandshakeCompletionEvent.SUCCESS);
    // Do not configureDeferSslHandler(pipeline);
    configureConnectionContext(pipeline);
    configureRequestSend();
    configureConnectRequest();
    subscribeToProxyConnectionFactory();

    assertThat(subscriber.isErrored(), is(true));
    Throwable error = subscriber.error();
    assertThat(error, is(notNullValue()));
    assertThat(error, instanceOf(IllegalStateException.class));
    assertThat(error.getMessage(), containsString(DeferSslHandler.class.getSimpleName()));
    assertConnectPayloadConsumed(false);
    assertConnectionClosed();
}
 
Example #16
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 #17
Source File: ProtocolNegotiatorsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void tlsHandler_userEventTriggeredSslEvent_supportedProtocolH2() throws Exception {
  SslHandler goodSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "h2";
    }
  };

  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 #18
Source File: ProtocolNegotiatorsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void tlsHandler_userEventTriggeredSslEvent_unsupportedProtocol() throws Exception {
  SslHandler badSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "badprotocol";
    }
  };

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

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

  pipeline.fireUserEventTriggered(sslEvent);

  // No h2 protocol was specified, so this should be closed.
  assertFalse(channel.isOpen());
  ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
  assertNull(grpcHandlerCtx);
}
 
Example #19
Source File: ProxyConnectConnectionFactoryFilterTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Test
public void successfulConnect() {
    ChannelPipeline pipeline = configurePipeline(SslHandshakeCompletionEvent.SUCCESS);
    configureDeferSslHandler(pipeline);
    configureConnectionContext(pipeline);
    configureRequestSend();
    configureConnectRequest();
    subscribeToProxyConnectionFactory();

    assertThat(subscriber.isSuccess(), is(true));
    assertThat(subscriber.result(), is(sameInstance(this.connection)));
    assertConnectPayloadConsumed(true);
    assertThat("Connection closed", connectionClose.isSubscribed(), is(false));
}
 
Example #20
Source File: SocketSslEchoTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public final void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof SslHandshakeCompletionEvent) {
        SslHandshakeCompletionEvent handshakeEvt = (SslHandshakeCompletionEvent) evt;
        if (handshakeEvt.cause() != null) {
            logger.warn("Handshake failed:", handshakeEvt.cause());
        }
        assertSame(SslHandshakeCompletionEvent.SUCCESS, evt);
        negoCounter.incrementAndGet();
        logStats("HANDSHAKEN");
    }
}
 
Example #21
Source File: SslProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
	if (evt instanceof SslHandshakeCompletionEvent) {
		handshakeDone = true;
		if (ctx.pipeline()
		       .context(this) != null) {
			ctx.pipeline()
			   .remove(this);
		}
		SslHandshakeCompletionEvent handshake = (SslHandshakeCompletionEvent) evt;
		if (handshake.isSuccess()) {
			if (recorder != null) {
				recorder.recordTlsHandshakeTime(
						ctx.channel().remoteAddress(),
						Duration.ofNanos(System.nanoTime() - tlsHandshakeTimeStart),
						SUCCESS);
			}
			ctx.fireChannelActive();
		}
		else {
			if (recorder != null) {
				recorder.recordTlsHandshakeTime(
						ctx.channel().remoteAddress(),
						Duration.ofNanos(System.nanoTime() - tlsHandshakeTimeStart),
						ERROR);
			}
			ctx.fireExceptionCaught(handshake.cause());
		}
	}
	ctx.fireUserEventTriggered(evt);
}
 
Example #22
Source File: SslBridgeHandler.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof SslState) {
        handleSslState(ctx, (SslState) evt);
        // Ignore event trigger for next handler, because it used only by this handler.
        return;
    }

    if (SslHandshakeCompletionEvent.SUCCESS == evt) {
        handleSslCompleted(ctx);
    }

    super.userEventTriggered(ctx, evt);
}
 
Example #23
Source File: ProxyConnectConnectionFactoryFilterTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private ChannelPipeline configurePipeline(@Nullable SslHandshakeCompletionEvent event) {
    ChannelPipeline pipeline = mock(ChannelPipeline.class);
    when(pipeline.addLast(any())).then((Answer<ChannelPipeline>) invocation -> {
        ChannelInboundHandler handshakeAwait = invocation.getArgument(0);
        if (event != null) {
            handshakeAwait.userEventTriggered(mock(ChannelHandlerContext.class), event);
        }
        return pipeline;
    });
    return pipeline;
}
 
Example #24
Source File: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void tlsHandler_userEventTriggeredSslEvent_unsupportedProtocol() throws Exception {
  SslHandler badSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "badprotocol";
    }
  };

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

  final AtomicReference<Throwable> error = new AtomicReference<>();
  ChannelHandler errorCapture = new ChannelInboundHandlerAdapter() {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
      error.set(cause);
    }
  };

  pipeline.addLast(errorCapture);

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

  pipeline.fireUserEventTriggered(sslEvent);

  // No h2 protocol was specified, so there should be an error, (normally handled by WBAEH)
  assertThat(error.get()).hasMessageThat().contains("Unable to find compatible protocol");
  ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
  assertNull(grpcHandlerCtx);
}
 
Example #25
Source File: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void serverTlsHandler_userEventTriggeredSslEvent_supportedProtocolCustom()
    throws Exception {
  SslHandler goodSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "managed_mtls";
    }
  };

  File serverCert = TestUtils.loadCert("server1.pem");
  File key = TestUtils.loadCert("server1.key");
  List<String> alpnList = Arrays.asList("managed_mtls", "h2");
  ApplicationProtocolConfig apn = new ApplicationProtocolConfig(
      ApplicationProtocolConfig.Protocol.ALPN,
      ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
      ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
      alpnList);

  sslContext = GrpcSslContexts.forServer(serverCert, key)
      .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
      .applicationProtocolConfig(apn).build();

  ChannelHandler handler = new ServerTlsHandler(grpcHandler, sslContext, null);
  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 #26
Source File: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void clientTlsHandler_userEventTriggeredSslEvent_supportedProtocolCustom()
    throws Exception {
  SslHandler goodSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "managed_mtls";
    }
  };
  DefaultEventLoopGroup elg = new DefaultEventLoopGroup(1);

  File clientCert = TestUtils.loadCert("client.pem");
  File key = TestUtils.loadCert("client.key");
  List<String> alpnList = Arrays.asList("managed_mtls", "h2");
  ApplicationProtocolConfig apn = new ApplicationProtocolConfig(
      ApplicationProtocolConfig.Protocol.ALPN,
      ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
      ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
      alpnList);

  sslContext = GrpcSslContexts.forClient()
      .keyManager(clientCert, key)
      .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
      .applicationProtocolConfig(apn).build();

  ClientTlsHandler handler = new ClientTlsHandler(grpcHandler, sslContext, "authority", elg);
  pipeline.addLast(handler);
  pipeline.replace(SslHandler.class, null, goodSslHandler);
  pipeline.fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT);
  channelHandlerCtx = pipeline.context(handler);
  Object sslEvent = SslHandshakeCompletionEvent.SUCCESS;

  pipeline.fireUserEventTriggered(sslEvent);

  ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
  assertNotNull(grpcHandlerCtx);
}
 
Example #27
Source File: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void clientTlsHandler_userEventTriggeredSslEvent_unsupportedProtocol() throws Exception {
  SslHandler goodSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "badproto";
    }
  };
  DefaultEventLoopGroup elg = new DefaultEventLoopGroup(1);

  ClientTlsHandler handler = new ClientTlsHandler(grpcHandler, sslContext, "authority", elg);
  pipeline.addLast(handler);

  final AtomicReference<Throwable> error = new AtomicReference<>();
  ChannelHandler errorCapture = new ChannelInboundHandlerAdapter() {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
      error.set(cause);
    }
  };

  pipeline.addLast(errorCapture);
  pipeline.replace(SslHandler.class, null, goodSslHandler);
  pipeline.fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT);
  channelHandlerCtx = pipeline.context(handler);
  Object sslEvent = SslHandshakeCompletionEvent.SUCCESS;

  pipeline.fireUserEventTriggered(sslEvent);

  // Bad protocol was specified, so there should be an error, (normally handled by WBAEH)
  assertThat(error.get()).hasMessageThat().contains("Unable to find compatible protocol");
  ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
  assertNull(grpcHandlerCtx);
}
 
Example #28
Source File: OriginResponseReceiver.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof CompleteEvent) {
        final CompleteReason reason = ((CompleteEvent) evt).getReason();
        if ((reason != SESSION_COMPLETE) && (edgeProxy != null)) {
            LOG.error("Origin request completed with reason other than COMPLETE: {}, {}",
                    reason.name(), ChannelUtils.channelInfoForLogging(ctx.channel()));
            final ZuulException ze = new ZuulException("CompleteEvent", reason.name(), true);
            edgeProxy.errorFromOrigin(ze);
        }

        // First let this event propagate along the pipeline, before cleaning vars from the channel.
        // See channelWrite() where these vars are first set onto the channel.
        try {
            super.userEventTriggered(ctx, evt);
        }
        finally {
            postCompleteHook(ctx, evt);
        }
    }
    else if (evt instanceof SslHandshakeCompletionEvent && !((SslHandshakeCompletionEvent) evt).isSuccess()) {
        Throwable cause = ((SslHandshakeCompletionEvent) evt).cause();
        ctx.channel().attr(SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE).set(cause);
    }
    else if (evt instanceof IdleStateEvent) {
        if (edgeProxy != null) {
            LOG.error("Origin request received IDLE event: {}", ChannelUtils.channelInfoForLogging(ctx.channel()));
            edgeProxy.errorFromOrigin(new OutboundException(READ_TIMEOUT, edgeProxy.getRequestAttempts()));
        }
        super.userEventTriggered(ctx, evt);
    }
    else {
        super.userEventTriggered(ctx, evt);
    }
}
 
Example #29
Source File: SslHandshakeInfoHandler.java    From zuul with Apache License 2.0 5 votes vote down vote up
private void incrementCounters(
        SslHandshakeCompletionEvent sslHandshakeCompletionEvent, SslHandshakeInfo handshakeInfo) {
    if (spectatorRegistry == null) {
        // May be null for testing.
        return;
    }
    try {
        if (sslHandshakeCompletionEvent.isSuccess()) {
            String proto = handshakeInfo.getProtocol().length() > 0 ? handshakeInfo.getProtocol() : "unknown";
            String ciphsuite =
                    handshakeInfo.getCipherSuite().length() > 0 ? handshakeInfo.getCipherSuite() : "unknown";
            spectatorRegistry.counter("server.ssl.handshake",
                    "success", String.valueOf(sslHandshakeCompletionEvent.isSuccess()),
                    "protocol", String.valueOf(proto),
                    "ciphersuite", String.valueOf(ciphsuite),
                    "clientauth", String.valueOf(handshakeInfo.getClientAuthRequirement())
                                     )
                    .increment();
        }
        else {
            spectatorRegistry.counter("server.ssl.handshake",
                    "success", String.valueOf(sslHandshakeCompletionEvent.isSuccess()),
                    "failure_cause", String.valueOf(sslHandshakeCompletionEvent.cause())
                                     )
                    .increment();
        }
    } catch (Exception e) {
        LOG.error("Error incrememting counters for SSL handshake!", e);
    }
}
 
Example #30
Source File: SslClientCertificateHandlerTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Test
public void test_peer_not_verified_but_required() throws SSLPeerUnverifiedException, InterruptedException {

    when(tls.getClientAuthMode()).thenReturn(Tls.ClientAuthMode.REQUIRED);
    when(sslSession.getPeerCertificates()).thenThrow(new SSLPeerUnverifiedException("peer not verified"));
    channel.pipeline().fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS);

    verify(eventLog).clientWasDisconnected(eq(channel), anyString());
}