Skip to content

Commit a4b51dd

Browse files
Michael Bildnernormanmaurer
authored andcommitted
Do not bother closing SSL enging inbound if the outbound has already been closed.
Motivation: Invoking the javax.net.ssl.SSLEngine.closeInbound() method will send a fatal alert and invalidate the SSL session if a close_notify alert has not been received. From the javadoc: If the application initiated the closing process by calling closeOutbound(), under some circumstances it is not required that the initiator wait for the peer's corresponding close message. (See section 7.2.1 of the TLS specification (RFC 2246) for more information on waiting for closure alerts.) In such cases, this method need not be called. Always invoking the closeInbound() method without regard to whether or not the closeOutbound() method has been invoked could lead to invalidating perfectly valid SSL sessions. Modifications: Added an instance variable to track whether the SSLEngine.closeOutbound() method has been invoked. When the instance variable is true, the SSLEngine.closeInbound() method doesn't need to be invoked. Result: SSL sessions will not be invalidated if the outbound side has been closed but a close_notify alert hasn't been received.
1 parent e751231 commit a4b51dd

File tree

2 files changed

+241
-11
lines changed

2 files changed

+241
-11
lines changed

handler/src/main/java/io/netty/handler/ssl/SslHandler.java

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,8 @@ public class SslHandler extends ByteToMessageDecoder {
230230
*/
231231
private boolean needsFlush;
232232

233+
private boolean outboundClosed;
234+
233235
private int packetLength;
234236

235237
/**
@@ -367,6 +369,7 @@ public ChannelFuture close(final ChannelPromise future) {
367369
ctx.executor().execute(new Runnable() {
368370
@Override
369371
public void run() {
372+
SslHandler.this.outboundClosed = true;
370373
engine.closeOutbound();
371374
try {
372375
write(ctx, Unpooled.EMPTY_BUFFER, future);
@@ -659,7 +662,7 @@ private SSLEngineResult wrap(ByteBufAllocator alloc, SSLEngine engine, ByteBuf i
659662
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
660663
// Make sure to release SSLEngine,
661664
// and notify the handshake future if the connection has been closed during handshake.
662-
setHandshakeFailure(ctx, CHANNEL_CLOSED);
665+
setHandshakeFailure(ctx, CHANNEL_CLOSED, !outboundClosed);
663666
super.channelInactive(ctx);
664667
}
665668

@@ -1157,20 +1160,29 @@ private void setHandshakeSuccess() {
11571160
* Notify all the handshake futures about the failure during the handshake.
11581161
*/
11591162
private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause) {
1163+
setHandshakeFailure(ctx, cause, true);
1164+
}
1165+
1166+
/**
1167+
* Notify all the handshake futures about the failure during the handshake.
1168+
*/
1169+
private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boolean closeInbound) {
11601170
// Release all resources such as internal buffers that SSLEngine
11611171
// is managing.
11621172
engine.closeOutbound();
11631173

1164-
try {
1165-
engine.closeInbound();
1166-
} catch (SSLException e) {
1167-
// only log in debug mode as it most likely harmless and latest chrome still trigger
1168-
// this all the time.
1169-
//
1170-
// See https://github.com/netty/netty/issues/1340
1171-
String msg = e.getMessage();
1172-
if (msg == null || !msg.contains("possible truncation attack")) {
1173-
logger.debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e);
1174+
if (closeInbound) {
1175+
try {
1176+
engine.closeInbound();
1177+
} catch (SSLException e) {
1178+
// only log in debug mode as it most likely harmless and latest chrome still trigger
1179+
// this all the time.
1180+
//
1181+
// See https://github.com/netty/netty/issues/1340
1182+
String msg = e.getMessage();
1183+
if (msg == null || !msg.contains("possible truncation attack")) {
1184+
logger.debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e);
1185+
}
11741186
}
11751187
}
11761188
notifyHandshakeFailure(cause);
@@ -1195,6 +1207,7 @@ private void closeOutboundAndChannel(
11951207
return;
11961208
}
11971209

1210+
outboundClosed = true;
11981211
engine.closeOutbound();
11991212

12001213
ChannelPromise closeNotifyFuture = ctx.newPromise();
Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
/*
2+
* Copyright 2015 The Netty Project
3+
*
4+
* The Netty Project licenses this file to you under the Apache License,
5+
* version 2.0 (the "License"); you may not use this file except in compliance
6+
* with the License. You may obtain a copy of the License at:
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations
14+
* under the License.
15+
*/
16+
package io.netty.testsuite.transport.socket;
17+
18+
import io.netty.bootstrap.Bootstrap;
19+
import io.netty.bootstrap.ServerBootstrap;
20+
import io.netty.buffer.ByteBuf;
21+
import io.netty.buffer.ByteBufUtil;
22+
import io.netty.buffer.Unpooled;
23+
import io.netty.channel.Channel;
24+
import io.netty.channel.ChannelHandlerContext;
25+
import io.netty.channel.ChannelHandler.Sharable;
26+
import io.netty.channel.ChannelInitializer;
27+
import io.netty.channel.SimpleChannelInboundHandler;
28+
import io.netty.channel.socket.SocketChannel;
29+
import io.netty.handler.ssl.JdkSslClientContext;
30+
import io.netty.handler.ssl.JdkSslContext;
31+
import io.netty.handler.ssl.JdkSslServerContext;
32+
import io.netty.handler.ssl.SslContext;
33+
import io.netty.handler.ssl.SslHandler;
34+
import io.netty.handler.ssl.util.SelfSignedCertificate;
35+
import io.netty.util.internal.logging.InternalLogger;
36+
import io.netty.util.internal.logging.InternalLoggerFactory;
37+
38+
import org.junit.Test;
39+
import org.junit.runner.RunWith;
40+
import org.junit.runners.Parameterized;
41+
import org.junit.runners.Parameterized.Parameters;
42+
43+
import javax.net.ssl.SSLEngine;
44+
import javax.net.ssl.SSLSessionContext;
45+
46+
import java.io.File;
47+
import java.io.IOException;
48+
import java.net.InetSocketAddress;
49+
import java.security.cert.CertificateException;
50+
import java.util.Collection;
51+
import java.util.Collections;
52+
import java.util.Enumeration;
53+
import java.util.HashSet;
54+
import java.util.Set;
55+
import java.util.concurrent.atomic.AtomicReference;
56+
57+
import static org.junit.Assert.*;
58+
59+
@RunWith(Parameterized.class)
60+
public class SocketSslSessionReuseTest extends AbstractSocketTest {
61+
62+
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocketSslSessionReuseTest.class);
63+
64+
private static final File CERT_FILE;
65+
private static final File KEY_FILE;
66+
67+
static {
68+
SelfSignedCertificate ssc;
69+
try {
70+
ssc = new SelfSignedCertificate();
71+
} catch (CertificateException e) {
72+
throw new Error(e);
73+
}
74+
CERT_FILE = ssc.certificate();
75+
KEY_FILE = ssc.privateKey();
76+
}
77+
78+
@Parameters(name = "{index}: serverEngine = {0}, clientEngine = {1}")
79+
public static Collection<Object[]> data() throws Exception {
80+
return Collections.singletonList(new Object[] {
81+
new JdkSslServerContext(CERT_FILE, KEY_FILE),
82+
new JdkSslClientContext(CERT_FILE)
83+
});
84+
}
85+
86+
private final SslContext serverCtx;
87+
private final SslContext clientCtx;
88+
89+
public SocketSslSessionReuseTest(SslContext serverCtx, SslContext clientCtx) {
90+
this.serverCtx = serverCtx;
91+
this.clientCtx = clientCtx;
92+
}
93+
94+
@Test(timeout = 30000)
95+
public void testSslSessionReuse() throws Throwable {
96+
run();
97+
}
98+
99+
public void testSslSessionReuse(ServerBootstrap sb, Bootstrap cb) throws Throwable {
100+
final ReadAndDiscardHandler sh = new ReadAndDiscardHandler(true, true);
101+
final ReadAndDiscardHandler ch = new ReadAndDiscardHandler(false, true);
102+
final String[] protocols = new String[]{ "TLSv1", "TLSv1.1", "TLSv1.2" };
103+
104+
sb.childHandler(new ChannelInitializer<SocketChannel>() {
105+
@Override
106+
protected void initChannel(SocketChannel sch) throws Exception {
107+
SSLEngine engine = serverCtx.newEngine(sch.alloc());
108+
engine.setUseClientMode(false);
109+
engine.setEnabledProtocols(protocols);
110+
111+
sch.pipeline().addLast(new SslHandler(engine));
112+
sch.pipeline().addLast(sh);
113+
}
114+
});
115+
final Channel sc = sb.bind().sync().channel();
116+
117+
cb.handler(new ChannelInitializer<SocketChannel>() {
118+
@Override
119+
protected void initChannel(SocketChannel sch) throws Exception {
120+
InetSocketAddress serverAddr = (InetSocketAddress) sc.localAddress();
121+
SSLEngine engine = clientCtx.newEngine(sch.alloc(), serverAddr.getHostString(), serverAddr.getPort());
122+
engine.setUseClientMode(true);
123+
engine.setEnabledProtocols(protocols);
124+
125+
sch.pipeline().addLast(new SslHandler(engine));
126+
sch.pipeline().addLast(ch);
127+
}
128+
});
129+
130+
try {
131+
SSLSessionContext clientSessionCtx = ((JdkSslContext) clientCtx).sessionContext();
132+
ByteBuf msg = Unpooled.wrappedBuffer(new byte[] { 0xa, 0xb, 0xc, 0xd }, 0, 4);
133+
Channel cc = cb.connect().sync().channel();
134+
cc.writeAndFlush(msg).sync();
135+
cc.closeFuture().sync();
136+
rethrowHandlerExceptions(sh, ch);
137+
Set<String> sessions = sessionIdSet(clientSessionCtx.getIds());
138+
139+
msg = Unpooled.wrappedBuffer(new byte[] { 0xa, 0xb, 0xc, 0xd }, 0, 4);
140+
cc = cb.connect().sync().channel();
141+
cc.writeAndFlush(msg).sync();
142+
cc.closeFuture().sync();
143+
assertEquals("Expected no new sessions", sessions, sessionIdSet(clientSessionCtx.getIds()));
144+
rethrowHandlerExceptions(sh, ch);
145+
} finally {
146+
sc.close().awaitUninterruptibly();
147+
}
148+
}
149+
150+
private void rethrowHandlerExceptions(ReadAndDiscardHandler sh, ReadAndDiscardHandler ch) throws Throwable {
151+
if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
152+
throw sh.exception.get();
153+
}
154+
if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
155+
throw ch.exception.get();
156+
}
157+
if (sh.exception.get() != null) {
158+
throw sh.exception.get();
159+
}
160+
if (ch.exception.get() != null) {
161+
throw ch.exception.get();
162+
}
163+
}
164+
165+
private Set<String> sessionIdSet(Enumeration<byte[]> sessionIds) {
166+
Set<String> idSet = new HashSet<String>();
167+
byte[] id;
168+
while (sessionIds.hasMoreElements()) {
169+
id = sessionIds.nextElement();
170+
idSet.add(ByteBufUtil.hexDump(Unpooled.wrappedBuffer(id)));
171+
}
172+
return idSet;
173+
}
174+
175+
@Sharable
176+
private static class ReadAndDiscardHandler extends SimpleChannelInboundHandler<ByteBuf> {
177+
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
178+
private final boolean server;
179+
private final boolean autoRead;
180+
181+
ReadAndDiscardHandler(boolean server, boolean autoRead) {
182+
this.server = server;
183+
this.autoRead = autoRead;
184+
}
185+
186+
@Override
187+
public void messageReceived(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
188+
byte[] actual = new byte[in.readableBytes()];
189+
in.readBytes(actual);
190+
ctx.close();
191+
}
192+
193+
@Override
194+
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
195+
try {
196+
ctx.flush();
197+
} finally {
198+
if (!autoRead) {
199+
ctx.read();
200+
}
201+
}
202+
}
203+
204+
@Override
205+
public void exceptionCaught(ChannelHandlerContext ctx,
206+
Throwable cause) throws Exception {
207+
if (logger.isWarnEnabled()) {
208+
logger.warn(
209+
"Unexpected exception from the " +
210+
(server? "server" : "client") + " side", cause);
211+
}
212+
213+
exception.compareAndSet(null, cause);
214+
ctx.close();
215+
}
216+
}
217+
}

0 commit comments

Comments
 (0)