Skip to content

Commit

Permalink
Propagate TLS handshake exception in SslCompletionEvent (#4950)
Browse files Browse the repository at this point in the history
Motivation:

- `SslCompletionEvent` can have a cause if a TLS handshake is completed
exceptionally. As the cause isn't taken into account, users could see
the root cause of the failure.

- A legacy HTTPS server such as Microsoft-IIS/8.5 resets the connection
if no cipher suites in common without respecting the handshake process.
No hint is given to the handshake failure, users don't know why Armeria
can't communicate with the server.

Modifications:

- If `SslCompletionEvent` is not successful, propagate the cause to the
session promise.
- If an exception is raised during a handshake, create
`IllegalStateException` with a hint and add it as a suppressed
exception.

Result:

Exceptions that occurred during a TLS handshake are properly propagated
to users.
  • Loading branch information
ikhoon committed Jul 5, 2023
1 parent cdb2d02 commit 2e50636
Show file tree
Hide file tree
Showing 3 changed files with 121 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,8 @@ private void configureAsHttps(Channel ch, SocketAddress remoteAddr) {
p.addLast(configureSslHandler(sslHandler));
p.addLast(TrafficLoggingHandler.CLIENT);
p.addLast(new ChannelInboundHandlerAdapter() {
private boolean handshakeFailed;
@Nullable
private Boolean handshakeFailed;

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
Expand All @@ -232,9 +233,9 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc
}

final SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
if (!handshakeEvent.isSuccess()) {
handshakeFailed = !handshakeEvent.isSuccess();
if (handshakeFailed) {
// The connection will be closed automatically by SslHandler.
handshakeFailed = true;
return;
}

Expand Down Expand Up @@ -281,6 +282,19 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (handshakeFailed == null) {
// An exception was raised before the handshake event was completed.
// A legacy HTTPS server such as Microsoft-IIS/8.5 may reset the connection
// if no cipher suites in common.
final String tlsVersion = sslHandler.engine().getSession().getProtocol();
final IllegalStateException maybeHandshakeException = new IllegalStateException(
"An unexpected exception during TLS handshake. " +
"Possible reasons: no cipher suites in common, unsupported TLS version, etc. " +
"(TLS version: " + tlsVersion + ", cipher suites: " + sslCtx.cipherSuites() + ')',
cause);
HttpSessionHandler.setPendingException(ctx, maybeHandshakeException);
return;
}
if (handshakeFailed &&
cause instanceof DecoderException &&
cause.getCause() instanceof SSLException) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,7 @@
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.proxy.ProxyConnectException;
import io.netty.handler.proxy.ProxyConnectionEvent;
import io.netty.handler.ssl.SslCloseCompletionEvent;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
import io.netty.handler.ssl.SslCompletionEvent;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Promise;
Expand Down Expand Up @@ -411,9 +410,26 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc
return;
}

if (evt instanceof SslCompletionEvent) {
final SslCompletionEvent sslCompletionEvent = (SslCompletionEvent) evt;
if (sslCompletionEvent.isSuccess()) {
// Expected event
} else {
Throwable handshakeException = sslCompletionEvent.cause();
final Throwable pendingException = getPendingException(ctx);
if (pendingException != null && handshakeException != pendingException) {
// Use pendingException as the primary cause.
pendingException.addSuppressed(handshakeException);
handshakeException = pendingException;
}
sessionTimeoutFuture.cancel(false);
sessionPromise.tryFailure(handshakeException);
ctx.close();
}
return;
}

if (evt instanceof Http2ConnectionPrefaceAndSettingsFrameWrittenEvent ||
evt instanceof SslHandshakeCompletionEvent ||
evt instanceof SslCloseCompletionEvent ||
evt instanceof ChannelInputShutdownReadComplete) {
// Expected events
return;
Expand Down Expand Up @@ -456,7 +472,7 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
final HttpResponseDecoder responseDecoder = this.responseDecoder;
final Throwable pendingException;
if (responseDecoder != null && responseDecoder.hasUnfinishedResponses()) {
pendingException = getPendingException(ctx);
pendingException = maybeGetPendingException(ctx);
responseDecoder.failUnfinishedResponses(pendingException);
} else {
pendingException = null;
Expand All @@ -467,7 +483,7 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
sessionTimeoutFuture.cancel(false);
if (!sessionPromise.isDone()) {
sessionPromise.tryFailure(pendingException != null ? pendingException
: getPendingException(ctx));
: maybeGetPendingException(ctx));
}
}
}
Expand All @@ -489,12 +505,21 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E
}
}

private static Throwable maybeGetPendingException(ChannelHandlerContext ctx) {
final Throwable pendingException = getPendingException(ctx);
if (pendingException != null) {
return pendingException;
}
return ClosedSessionException.get();
}

@Nullable
private static Throwable getPendingException(ChannelHandlerContext ctx) {
if (ctx.channel().hasAttr(PENDING_EXCEPTION)) {
return ctx.channel().attr(PENDING_EXCEPTION).get();
}

return ClosedSessionException.get();
return null;
}

static void setPendingException(ChannelHandlerContext ctx, Throwable cause) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright 2023 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package com.linecorp.armeria.client;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.catchThrowable;

import java.nio.channels.ClosedChannelException;

import javax.net.ssl.SSLHandshakeException;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.api.extension.RegisterExtension;

import com.linecorp.armeria.common.HttpResponse;
import com.linecorp.armeria.server.ServerBuilder;
import com.linecorp.armeria.testing.junit5.server.ServerExtension;

@DisabledOnOs(value = OS.WINDOWS, disabledReason = "Windows may be a different order of closing events.")
class IisServerCompatibilityTest {

@RegisterExtension
static ServerExtension server = new ServerExtension() {
@Override
protected void configure(ServerBuilder sb) {
sb.https(0);
sb.tlsSelfSigned();
sb.childChannelPipelineCustomizer(pipeline -> {
// Simulate the behavior of IIS.
pipeline.channel().close();
});
sb.service("/", (ctx, req) -> HttpResponse.of("OK"));
}
};

@Test
void shouldRaiseSslHandleShakeExceptionWhenConnectionIsResetDuringTlsHandshake() {
final BlockingWebClient client = WebClient.builder(server.httpsUri())
.factory(ClientFactory.insecure())
.build()
.blocking();
final Throwable cause = catchThrowable(() -> client.get("/"));
assertThat(cause).isInstanceOf(UnprocessedRequestException.class)
.getCause().isInstanceOf(IllegalStateException.class)
.hasMessageFindingMatch(
"An unexpected exception during TLS handshake. " +
"Possible reasons: no cipher suites in common, unsupported TLS version," +
" etc. \\(TLS version: .*, cipher suites: .*\\)");
final Throwable suppressed0 = cause.getCause().getSuppressed()[0];
assertThat(suppressed0)
.isInstanceOf(ClosedChannelException.class);
assertThat(suppressed0.getSuppressed()[0])
.isInstanceOf(SSLHandshakeException.class)
.hasMessageContaining("Connection closed while SSL/TLS handshake was in progress");
}
}

0 comments on commit 2e50636

Please sign in to comment.