Java Code Examples for io.netty.handler.ssl.SslHandshakeCompletionEvent#isSuccess()

The following examples show how to use io.netty.handler.ssl.SslHandshakeCompletionEvent#isSuccess() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
Source File: ProtocolNegotiators.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
  if (evt instanceof SslHandshakeCompletionEvent) {
    SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
    if (handshakeEvent.isSuccess()) {
      if (NEXT_PROTOCOL_VERSIONS.contains(sslHandler(ctx.pipeline()).applicationProtocol())) {
        SSLSession session = sslHandler(ctx.pipeline()).engine().getSession();
        // Successfully negotiated the protocol.
        // Notify about completion and pass down SSLSession in attributes.
        grpcHandler.handleProtocolNegotiationCompleted(
            Attributes.newBuilder()
                .set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session)
                .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, ctx.channel().remoteAddress())
                .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, ctx.channel().localAddress())
                .build(),
            new InternalChannelz.Security(new InternalChannelz.Tls(session)));
        // Replace this handler with the GRPC handler.
        ctx.pipeline().replace(this, null, grpcHandler);
      } else {
        fail(ctx, new Exception(
            "Failed protocol negotiation: Unable to find compatible protocol."));
      }
    } else {
      fail(ctx, handshakeEvent.cause());
    }
  }
  super.userEventTriggered(ctx, evt);
}
 
Example 8
Source File: ProtocolNegotiators.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public void userEventTriggered(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 (NEXT_PROTOCOL_VERSIONS.contains(handler.applicationProtocol())) {
        // Successfully negotiated the protocol.
        logSslEngineDetails(Level.FINER, ctx, "TLS negotiation succeeded.", null);

        // Wait until negotiation is complete to add gRPC.   If added too early, HTTP/2 writes
        // will fail before we see the userEvent, and the channel is closed down prematurely.
        ctx.pipeline().addBefore(ctx.name(), null, grpcHandler);

        SSLSession session = handler.engine().getSession();
        // Successfully negotiated the protocol.
        // Notify about completion and pass down SSLSession in attributes.
        grpcHandler.handleProtocolNegotiationCompleted(
            Attributes.newBuilder()
                .set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session)
                .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, ctx.channel().remoteAddress())
                .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, ctx.channel().localAddress())
                .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.PRIVACY_AND_INTEGRITY)
                .build(),
            new InternalChannelz.Security(new InternalChannelz.Tls(session)));
        writeBufferedAndRemove(ctx);
      } else {
        Exception ex = new Exception(
            "Failed ALPN negotiation: Unable to find compatible protocol.");
        logSslEngineDetails(Level.FINE, ctx, "TLS negotiation failed.", ex);
        fail(ctx, ex);
      }
    } else {
      fail(ctx, handshakeEvent.cause());
    }
  }
  super.userEventTriggered(ctx, evt);
}
 
Example 9
Source File: SslClientCertificateHandler.java    From hivemq-community-edition with Apache License 2.0 5 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 SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) evt;

    if (!sslHandshakeCompletionEvent.isSuccess()) {
        log.trace("Handshake failed", sslHandshakeCompletionEvent.cause());
        return;
    }

    final Channel channel = ctx.channel();

    try {
        final SslHandler sslHandler = (SslHandler) channel.pipeline().get(ChannelHandlerNames.SSL_HANDLER);

        final SSLSession session = sslHandler.engine().getSession();
        final Certificate[] peerCertificates = session.getPeerCertificates();
        final SslClientCertificate sslClientCertificate = new SslClientCertificateImpl(peerCertificates);
        channel.attr(ChannelAttributes.AUTH_CERTIFICATE).set(sslClientCertificate);

    } catch (final SSLPeerUnverifiedException e) {
        handleSslPeerUnverifiedException(channel, e);

    } catch (final ClassCastException e2) {
        eventLog.clientWasDisconnected(channel, "SSL handshake failed");
        channel.close();
        throw new RuntimeException("Not able to get SslHandler from pipeline", e2);
    }

    channel.pipeline().remove(this);

}
 
Example 10
Source File: OcspClientHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof SslHandshakeCompletionEvent) {
        ctx.pipeline().remove(this);

        SslHandshakeCompletionEvent event = (SslHandshakeCompletionEvent) evt;
        if (event.isSuccess() && !verify(ctx, engine)) {
            throw OCSP_VERIFICATION_EXCEPTION;
        }
    }

    ctx.fireUserEventTriggered(evt);
}
 
Example 11
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 12
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);
    }
}