1 /*
2 * Copyright 2012 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 * https://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.handler.ssl;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.ByteBufAllocator;
20 import io.netty.buffer.ByteBufUtil;
21 import io.netty.buffer.CompositeByteBuf;
22 import io.netty.buffer.Unpooled;
23 import io.netty.channel.Channel;
24 import io.netty.channel.ChannelConfig;
25 import io.netty.channel.ChannelException;
26 import io.netty.channel.ChannelFuture;
27 import io.netty.channel.ChannelFutureListener;
28 import io.netty.channel.ChannelHandlerContext;
29 import io.netty.channel.ChannelInboundHandler;
30 import io.netty.channel.ChannelOption;
31 import io.netty.channel.ChannelOutboundBuffer;
32 import io.netty.channel.ChannelOutboundHandler;
33 import io.netty.channel.ChannelPipeline;
34 import io.netty.channel.ChannelPromise;
35 import io.netty.channel.DefaultChannelPromise;
36 import io.netty.channel.StacklessClosedChannelException;
37 import io.netty.channel.unix.UnixChannel;
38 import io.netty.handler.codec.ByteToMessageDecoder;
39 import io.netty.handler.codec.DecoderException;
40 import io.netty.handler.codec.UnsupportedMessageTypeException;
41 import io.netty.util.ReferenceCountUtil;
42 import io.netty.util.concurrent.DefaultPromise;
43 import io.netty.util.concurrent.EventExecutor;
44 import io.netty.util.concurrent.Future;
45 import io.netty.util.concurrent.ImmediateExecutor;
46 import io.netty.util.concurrent.Promise;
47 import io.netty.util.concurrent.PromiseNotifier;
48 import io.netty.util.internal.ObjectUtil;
49 import io.netty.util.internal.PlatformDependent;
50 import io.netty.util.internal.ThrowableUtil;
51 import io.netty.util.internal.UnstableApi;
52 import io.netty.util.internal.logging.InternalLogger;
53 import io.netty.util.internal.logging.InternalLoggerFactory;
54
55 import java.io.IOException;
56 import java.net.SocketAddress;
57 import java.nio.ByteBuffer;
58 import java.nio.channels.ClosedChannelException;
59 import java.nio.channels.DatagramChannel;
60 import java.nio.channels.SocketChannel;
61 import java.security.cert.CertificateException;
62 import java.util.ArrayDeque;
63 import java.util.List;
64 import java.util.concurrent.Executor;
65 import java.util.concurrent.RejectedExecutionException;
66 import java.util.concurrent.TimeUnit;
67 import java.util.regex.Pattern;
68
69 import javax.net.ssl.SSLEngine;
70 import javax.net.ssl.SSLEngineResult;
71 import javax.net.ssl.SSLEngineResult.HandshakeStatus;
72 import javax.net.ssl.SSLEngineResult.Status;
73 import javax.net.ssl.SSLException;
74 import javax.net.ssl.SSLHandshakeException;
75 import javax.net.ssl.SSLSession;
76
77 import static io.netty.handler.ssl.SslUtils.NOT_ENOUGH_DATA;
78 import static io.netty.handler.ssl.SslUtils.getEncryptedPacketLength;
79 import static io.netty.util.internal.ObjectUtil.checkNotNull;
80 import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
81
82 /**
83 * Adds <a href="https://en.wikipedia.org/wiki/Transport_Layer_Security">SSL
84 * · TLS</a> and StartTLS support to a {@link Channel}. Please refer
85 * to the <strong>"SecureChat"</strong> example in the distribution or the web
86 * site for the detailed usage.
87 *
88 * <h3>Beginning the handshake</h3>
89 * <p>
90 * Beside using the handshake {@link ChannelFuture} to get notified about the completion of the handshake it's
91 * also possible to detect it by implement the
92 * {@link ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)}
93 * method and check for a {@link SslHandshakeCompletionEvent}.
94 *
95 * <h3>Handshake</h3>
96 * <p>
97 * The handshake will be automatically issued for you once the {@link Channel} is active and
98 * {@link SSLEngine#getUseClientMode()} returns {@code true}.
99 * So no need to bother with it by your self.
100 *
101 * <h3>Closing the session</h3>
102 * <p>
103 * To close the SSL session, the {@link #closeOutbound()} method should be
104 * called to send the {@code close_notify} message to the remote peer. One
105 * exception is when you close the {@link Channel} - {@link SslHandler}
106 * intercepts the close request and send the {@code close_notify} message
107 * before the channel closure automatically. Once the SSL session is closed,
108 * it is not reusable, and consequently you should create a new
109 * {@link SslHandler} with a new {@link SSLEngine} as explained in the
110 * following section.
111 *
112 * <h3>Restarting the session</h3>
113 * <p>
114 * To restart the SSL session, you must remove the existing closed
115 * {@link SslHandler} from the {@link ChannelPipeline}, insert a new
116 * {@link SslHandler} with a new {@link SSLEngine} into the pipeline,
117 * and start the handshake process as described in the first section.
118 *
119 * <h3>Implementing StartTLS</h3>
120 * <p>
121 * <a href="https://en.wikipedia.org/wiki/STARTTLS">StartTLS</a> is the
122 * communication pattern that secures the wire in the middle of the plaintext
123 * connection. Please note that it is different from SSL · TLS, that
124 * secures the wire from the beginning of the connection. Typically, StartTLS
125 * is composed of three steps:
126 * <ol>
127 * <li>Client sends a StartTLS request to server.</li>
128 * <li>Server sends a StartTLS response to client.</li>
129 * <li>Client begins SSL handshake.</li>
130 * </ol>
131 * If you implement a server, you need to:
132 * <ol>
133 * <li>create a new {@link SslHandler} instance with {@code startTls} flag set
134 * to {@code true},</li>
135 * <li>insert the {@link SslHandler} to the {@link ChannelPipeline}, and</li>
136 * <li>write a StartTLS response.</li>
137 * </ol>
138 * Please note that you must insert {@link SslHandler} <em>before</em> sending
139 * the StartTLS response. Otherwise the client can send begin SSL handshake
140 * before {@link SslHandler} is inserted to the {@link ChannelPipeline}, causing
141 * data corruption.
142 * <p>
143 * The client-side implementation is much simpler.
144 * <ol>
145 * <li>Write a StartTLS request,</li>
146 * <li>wait for the StartTLS response,</li>
147 * <li>create a new {@link SslHandler} instance with {@code startTls} flag set
148 * to {@code false},</li>
149 * <li>insert the {@link SslHandler} to the {@link ChannelPipeline}, and</li>
150 * <li>Initiate SSL handshake.</li>
151 * </ol>
152 *
153 * <h3>Known issues</h3>
154 * <p>
155 * Because of a known issue with the current implementation of the SslEngine that comes
156 * with Java it may be possible that you see blocked IO-Threads while a full GC is done.
157 * <p>
158 * So if you are affected you can workaround this problem by adjust the cache settings
159 * like shown below:
160 *
161 * <pre>
162 * SslContext context = ...;
163 * context.getServerSessionContext().setSessionCacheSize(someSaneSize);
164 * context.getServerSessionContext().setSessionTime(someSameTimeout);
165 * </pre>
166 * <p>
167 * What values to use here depends on the nature of your application and should be set
168 * based on monitoring and debugging of it.
169 * For more details see
170 * <a href="https://github.com/netty/netty/issues/832">#832</a> in our issue tracker.
171 */
172 public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundHandler {
173 private static final InternalLogger logger =
174 InternalLoggerFactory.getInstance(SslHandler.class);
175 private static final Pattern IGNORABLE_ERROR_MESSAGE = Pattern.compile(
176 "^.*(?:connection.*(?:reset|closed|abort|broken)|broken.*pipe).*$", Pattern.CASE_INSENSITIVE);
177 private static final int STATE_SENT_FIRST_MESSAGE = 1;
178 private static final int STATE_FLUSHED_BEFORE_HANDSHAKE = 1 << 1;
179 private static final int STATE_READ_DURING_HANDSHAKE = 1 << 2;
180 private static final int STATE_HANDSHAKE_STARTED = 1 << 3;
181 /**
182 * Set by wrap*() methods when something is produced.
183 * {@link #channelReadComplete(ChannelHandlerContext)} will check this flag, clear it, and call ctx.flush().
184 */
185 private static final int STATE_NEEDS_FLUSH = 1 << 4;
186 private static final int STATE_OUTBOUND_CLOSED = 1 << 5;
187 private static final int STATE_CLOSE_NOTIFY = 1 << 6;
188 private static final int STATE_PROCESS_TASK = 1 << 7;
189 /**
190 * This flag is used to determine if we need to call {@link ChannelHandlerContext#read()} to consume more data
191 * when {@link ChannelConfig#isAutoRead()} is {@code false}.
192 */
193 private static final int STATE_FIRE_CHANNEL_READ = 1 << 8;
194 private static final int STATE_UNWRAP_REENTRY = 1 << 9;
195 /**
196 * Set when we stopped wrapping application data because too much of the encrypted data we wrote before was not
197 * written by the transport yet. Wrapping is resumed once enough of it was written and no delegated task is
198 * running, see {@link #resumeWrap(ChannelFuture)}.
199 */
200 private static final int STATE_WRAP_SUSPENDED = 1 << 10;
201 /**
202 * Set when wrapping was suspended, and cleared once all the queued data was wrapped. While it is set, the queued
203 * data is wrapped before the outbound side of the {@link SSLEngine} is closed, as it would be failed otherwise.
204 * It stays set once wrapping resumed, as {@link #wrap(ChannelHandlerContext, boolean)} only wraps one record at a
205 * time while the {@link SSLEngine} is handshaking.
206 */
207 private static final int STATE_WRAP_PENDING = 1 << 11;
208
209 /**
210 * <a href="https://tools.ietf.org/html/rfc5246#section-6.2">2^14</a> which is the maximum sized plaintext chunk
211 * allowed by the TLS RFC.
212 */
213 private static final int MAX_PLAINTEXT_LENGTH = 16 * 1024;
214
215 /**
216 * The JDK {@link SSLEngine} wants at least {@code packetLength - 5 - 16} bytes to unwrap a record, as it subtracts
217 * the 5 byte header and at least 16 bytes of tag or MAC for every cipher suite.
218 * <p>
219 * The {@code BUFFER_OVERFLOW} check calls {@code estimateFragmentSize(packetLen)}:
220 * https://github.com/openjdk/jdk/blob/6917797/src/java.base/share/classes/sun/security/ssl/SSLEngineImpl.java#L672
221 * which for AEAD ciphers subtracts the header and tag size from the packet length:
222 * https://github.com/openjdk/jdk/blob/6917797/src/java.base/share/classes/sun/security/ssl/SSLCipher.java#L1969
223 */
224 private static final int JDK_MIN_UNWRAP_OVERHEAD = 5 + 16;
225
226 private enum SslEngineType {
227 TCNATIVE(true, COMPOSITE_CUMULATOR) {
228 @Override
229 SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int len, ByteBuf out) throws SSLException {
230 int nioBufferCount = in.nioBufferCount();
231 int writerIndex = out.writerIndex();
232 final SSLEngineResult result;
233 if (nioBufferCount > 1) {
234 /*
235 * If {@link OpenSslEngine} is in use,
236 * we can use a special {@link OpenSslEngine#unwrap(ByteBuffer[], ByteBuffer[])} method
237 * that accepts multiple {@link ByteBuffer}s without additional memory copies.
238 */
239 ReferenceCountedOpenSslEngine opensslEngine = (ReferenceCountedOpenSslEngine) handler.engine;
240 try {
241 handler.singleBuffer[0] = toByteBuffer(out, writerIndex, out.writableBytes());
242 result = opensslEngine.unwrap(in.nioBuffers(in.readerIndex(), len), handler.singleBuffer);
243 } finally {
244 handler.singleBuffer[0] = null;
245 }
246 } else {
247 result = handler.engine.unwrap(toByteBuffer(in, in.readerIndex(), len),
248 toByteBuffer(out, writerIndex, out.writableBytes()));
249 }
250 out.writerIndex(writerIndex + result.bytesProduced());
251 return result;
252 }
253
254 @Override
255 ByteBuf allocateWrapBuffer(SslHandler handler, ByteBufAllocator allocator,
256 int pendingBytes, int numComponents) {
257 return allocator.directBuffer(((ReferenceCountedOpenSslEngine) handler.engine)
258 .calculateOutNetBufSize(pendingBytes, numComponents));
259 }
260
261 @Override
262 int calculateRequiredOutBufSpace(SslHandler handler, int pendingBytes, int numComponents) {
263 return ((ReferenceCountedOpenSslEngine) handler.engine)
264 .calculateMaxLengthForWrap(pendingBytes, numComponents);
265 }
266
267 @Override
268 int calculatePendingData(SslHandler handler, int guess) {
269 int sslPending = ((ReferenceCountedOpenSslEngine) handler.engine).sslPending();
270 return sslPending > 0 ? sslPending : guess;
271 }
272
273 @Override
274 int calculateInitialUnwrapBufSize(SslHandler handler, int length) {
275 // The plaintext of a record is never longer than MAX_PLAINTEXT_LENGTH.
276 return Math.min(length, MAX_PLAINTEXT_LENGTH);
277 }
278
279 @Override
280 boolean jdkCompatibilityMode(SSLEngine engine) {
281 return ((ReferenceCountedOpenSslEngine) engine).jdkCompatibilityMode;
282 }
283 },
284 CONSCRYPT(true, COMPOSITE_CUMULATOR) {
285 @Override
286 SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int len, ByteBuf out) throws SSLException {
287 int nioBufferCount = in.nioBufferCount();
288 int writerIndex = out.writerIndex();
289 final SSLEngineResult result;
290 if (nioBufferCount > 1) {
291 /*
292 * Use a special unwrap method without additional memory copies.
293 */
294 try {
295 handler.singleBuffer[0] = toByteBuffer(out, writerIndex, out.writableBytes());
296 result = ((ConscryptAlpnSslEngine) handler.engine).unwrap(
297 in.nioBuffers(in.readerIndex(), len),
298 handler.singleBuffer);
299 } finally {
300 handler.singleBuffer[0] = null;
301 }
302 } else {
303 result = handler.engine.unwrap(toByteBuffer(in, in.readerIndex(), len),
304 toByteBuffer(out, writerIndex, out.writableBytes()));
305 }
306 out.writerIndex(writerIndex + result.bytesProduced());
307 return result;
308 }
309
310 @Override
311 ByteBuf allocateWrapBuffer(SslHandler handler, ByteBufAllocator allocator,
312 int pendingBytes, int numComponents) {
313 return allocator.directBuffer(
314 ((ConscryptAlpnSslEngine) handler.engine).calculateOutNetBufSize(pendingBytes, numComponents));
315 }
316
317 @Override
318 int calculateRequiredOutBufSpace(SslHandler handler, int pendingBytes, int numComponents) {
319 return ((ConscryptAlpnSslEngine) handler.engine)
320 .calculateRequiredOutBufSpace(pendingBytes, numComponents);
321 }
322
323 @Override
324 int calculatePendingData(SslHandler handler, int guess) {
325 return guess;
326 }
327
328 @Override
329 int calculateInitialUnwrapBufSize(SslHandler handler, int length) {
330 // Conscrypt does not need more space than the plaintext, which is at most MAX_PLAINTEXT_LENGTH.
331 return Math.min(length, MAX_PLAINTEXT_LENGTH);
332 }
333
334 @Override
335 boolean jdkCompatibilityMode(SSLEngine engine) {
336 return true;
337 }
338 },
339 JDK(false, MERGE_CUMULATOR) {
340 @Override
341 SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int len, ByteBuf out) throws SSLException {
342 int writerIndex = out.writerIndex();
343 ByteBuffer inNioBuffer = getUnwrapInputBuffer(handler, toByteBuffer(in, in.readerIndex(), len));
344 int position = inNioBuffer.position();
345 final SSLEngineResult result = handler.engine.unwrap(inNioBuffer,
346 toByteBuffer(out, writerIndex, out.writableBytes()));
347 out.writerIndex(writerIndex + result.bytesProduced());
348
349 // This is a workaround for a bug in Android 5.0. Android 5.0 does not correctly update the
350 // SSLEngineResult.bytesConsumed() in some cases and just return 0.
351 //
352 // See:
353 // - https://android-review.googlesource.com/c/platform/external/conscrypt/+/122080
354 // - https://github.com/netty/netty/issues/7758
355 if (result.bytesConsumed() == 0) {
356 int consumed = inNioBuffer.position() - position;
357 if (consumed != result.bytesConsumed()) {
358 // Create a new SSLEngineResult with the correct bytesConsumed().
359 return new SSLEngineResult(
360 result.getStatus(), result.getHandshakeStatus(), consumed, result.bytesProduced());
361 }
362 }
363 return result;
364 }
365
366 private ByteBuffer getUnwrapInputBuffer(SslHandler handler, ByteBuffer inNioBuffer) {
367 int javaVersion = PlatformDependent.javaVersion();
368 if (javaVersion >= 22 && javaVersion < 25 && inNioBuffer.isDirect()) {
369 // Work-around for https://bugs.openjdk.org/browse/JDK-8357268
370 int remaining = inNioBuffer.remaining();
371 ByteBuffer copy = handler.unwrapInputCopy;
372 if (copy == null || copy.capacity() < remaining) {
373 handler.unwrapInputCopy = copy = ByteBuffer.allocate(remaining);
374 } else {
375 copy.clear();
376 }
377 copy.put(inNioBuffer).flip();
378 return copy;
379 }
380 return inNioBuffer;
381 }
382
383 @Override
384 ByteBuf allocateWrapBuffer(SslHandler handler, ByteBufAllocator allocator,
385 int pendingBytes, int numComponents) {
386 // For JDK we don't have a good source for the max wrap overhead. We need at least one packet buffer
387 // size, but may be able to fit more in based on the total requested.
388 return allocator.heapBuffer(Math.max(pendingBytes, handler.engine.getSession().getPacketBufferSize()));
389 }
390
391 @Override
392 int calculateRequiredOutBufSpace(SslHandler handler, int pendingBytes, int numComponents) {
393 // As for the JDK SSLEngine we always need to operate on buffer space required by the SSLEngine
394 // (normally ~16KB). This is required even if the amount of data to encrypt is very small. Use heap
395 // buffers to reduce the native memory usage.
396 //
397 // Beside this the JDK SSLEngine also (as of today) will do an extra heap to direct buffer copy
398 // if a direct buffer is used as its internals operate on byte[].
399 return handler.engine.getSession().getPacketBufferSize();
400 }
401
402 @Override
403 int calculatePendingData(SslHandler handler, int guess) {
404 return guess;
405 }
406
407 @Override
408 int calculateInitialUnwrapBufSize(SslHandler handler, int length) {
409 // length is a single record, which may need a bit more space than MAX_PLAINTEXT_LENGTH.
410 return length <= MAX_PLAINTEXT_LENGTH ? length : Math.max(MAX_PLAINTEXT_LENGTH,
411 length - JDK_MIN_UNWRAP_OVERHEAD);
412 }
413
414 @Override
415 boolean jdkCompatibilityMode(SSLEngine engine) {
416 return true;
417 }
418 };
419
420 static SslEngineType forEngine(SSLEngine engine) {
421 return engine instanceof ReferenceCountedOpenSslEngine ? TCNATIVE :
422 engine instanceof ConscryptAlpnSslEngine ? CONSCRYPT : JDK;
423 }
424
425 SslEngineType(boolean wantsDirectBuffer, Cumulator cumulator) {
426 this.wantsDirectBuffer = wantsDirectBuffer;
427 this.cumulator = cumulator;
428 }
429
430 abstract SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int len, ByteBuf out) throws SSLException;
431
432 abstract int calculatePendingData(SslHandler handler, int guess);
433
434 abstract int calculateInitialUnwrapBufSize(SslHandler handler, int length);
435
436 abstract boolean jdkCompatibilityMode(SSLEngine engine);
437
438 abstract ByteBuf allocateWrapBuffer(SslHandler handler, ByteBufAllocator allocator,
439 int pendingBytes, int numComponents);
440
441 abstract int calculateRequiredOutBufSpace(SslHandler handler, int pendingBytes, int numComponents);
442
443 // BEGIN Platform-dependent flags
444
445 /**
446 * {@code true} if and only if {@link SSLEngine} expects a direct buffer and so if a heap buffer
447 * is given will make an extra memory copy.
448 */
449 final boolean wantsDirectBuffer;
450
451 // END Platform-dependent flags
452
453 /**
454 * When using JDK {@link SSLEngine}, we use {@link #MERGE_CUMULATOR} because it works only with
455 * one {@link ByteBuffer}.
456 *
457 * When using {@link OpenSslEngine}, we can use {@link #COMPOSITE_CUMULATOR} because it has
458 * {@link OpenSslEngine#unwrap(ByteBuffer[], ByteBuffer[])} which works with multiple {@link ByteBuffer}s
459 * and which does not need to do extra memory copies.
460 */
461 final Cumulator cumulator;
462 }
463
464 private volatile ChannelHandlerContext ctx;
465 private final SSLEngine engine;
466 private final SslEngineType engineType;
467 private final Executor delegatedTaskExecutor;
468 private final boolean jdkCompatibilityMode;
469
470 /**
471 * Used if {@link SSLEngine#wrap(ByteBuffer[], ByteBuffer)} and {@link SSLEngine#unwrap(ByteBuffer, ByteBuffer[])}
472 * should be called with a {@link ByteBuf} that is only backed by one {@link ByteBuffer} to reduce the object
473 * creation.
474 */
475 private final ByteBuffer[] singleBuffer = new ByteBuffer[1];
476 private ByteBuffer unwrapInputCopy;
477
478 private final boolean startTls;
479 private final ResumptionController resumptionController;
480
481 private final SslTasksRunner sslTaskRunnerForUnwrap = new SslTasksRunner(true);
482 private final SslTasksRunner sslTaskRunner = new SslTasksRunner(false);
483
484 private SslHandlerCoalescingBufferQueue pendingUnencryptedWrites;
485 /**
486 * The writes of encrypted application data that may not be complete yet, oldest first, and the number of bytes
487 * they contain. Like the writability of the {@link Channel}, we stop wrapping once more than
488 * {@link ChannelConfig#getWriteBufferHighWaterMark()} bytes are pending, and continue once it is not more than
489 * {@link ChannelConfig#getWriteBufferLowWaterMark()} anymore. We can not use {@link Channel#isWritable()} for
490 * this, as the bytes queued in {@link #pendingUnencryptedWrites} count towards it as well.
491 */
492 private ArrayDeque<EncryptedWritePromise> pendingEncryptedWrites;
493 private long pendingEncryptedBytes;
494 /**
495 * The write we wait for while wrapping is suspended.
496 */
497 private ChannelFuture resumeWrapFuture;
498 private final ChannelFutureListener resumeWrapListener = this::resumeWrap;
499 /**
500 * Set if closing the outbound side has to wait for a delegated task, as the data for which wrapping was suspended
501 * needs to be wrapped first. Notified once the {@code close_notify} is written.
502 */
503 private ChannelPromise deferredCloseNotifyPromise;
504 private Promise<Channel> handshakePromise = new LazyChannelPromise();
505 private final LazyChannelPromise sslClosePromise = new LazyChannelPromise();
506
507 private int packetLength;
508 private short state;
509
510 private volatile long handshakeTimeoutMillis = 10000;
511 private volatile long closeNotifyFlushTimeoutMillis = 3000;
512 private volatile long closeNotifyReadTimeoutMillis;
513 volatile int wrapDataSize = MAX_PLAINTEXT_LENGTH;
514
515 /**
516 * Creates a new instance which runs all delegated tasks directly on the {@link EventExecutor}.
517 *
518 * @param engine the {@link SSLEngine} this handler will use
519 */
520 public SslHandler(SSLEngine engine) {
521 this(engine, false);
522 }
523
524 /**
525 * Creates a new instance which runs all delegated tasks directly on the {@link EventExecutor}.
526 *
527 * @param engine the {@link SSLEngine} this handler will use
528 * @param startTls {@code true} if the first write request shouldn't be
529 * encrypted by the {@link SSLEngine}
530 */
531 public SslHandler(SSLEngine engine, boolean startTls) {
532 this(engine, startTls, ImmediateExecutor.INSTANCE);
533 }
534
535 /**
536 * Creates a new instance.
537 *
538 * @param engine the {@link SSLEngine} this handler will use
539 * @param delegatedTaskExecutor the {@link Executor} that will be used to execute tasks that are returned by
540 * {@link SSLEngine#getDelegatedTask()}.
541 */
542 public SslHandler(SSLEngine engine, Executor delegatedTaskExecutor) {
543 this(engine, false, delegatedTaskExecutor);
544 }
545
546 /**
547 * Creates a new instance.
548 *
549 * @param engine the {@link SSLEngine} this handler will use
550 * @param startTls {@code true} if the first write request shouldn't be
551 * encrypted by the {@link SSLEngine}
552 * @param delegatedTaskExecutor the {@link Executor} that will be used to execute tasks that are returned by
553 * {@link SSLEngine#getDelegatedTask()}.
554 */
555 public SslHandler(SSLEngine engine, boolean startTls, Executor delegatedTaskExecutor) {
556 this(engine, startTls, delegatedTaskExecutor, null);
557 }
558
559 SslHandler(SSLEngine engine, boolean startTls, Executor delegatedTaskExecutor,
560 ResumptionController resumptionController) {
561 this.engine = ObjectUtil.checkNotNull(engine, "engine");
562 this.delegatedTaskExecutor = ObjectUtil.checkNotNull(delegatedTaskExecutor, "delegatedTaskExecutor");
563 engineType = SslEngineType.forEngine(engine);
564 this.startTls = startTls;
565 this.jdkCompatibilityMode = engineType.jdkCompatibilityMode(engine);
566 setCumulator(engineType.cumulator);
567 this.resumptionController = resumptionController;
568 }
569
570 public long getHandshakeTimeoutMillis() {
571 return handshakeTimeoutMillis;
572 }
573
574 public void setHandshakeTimeout(long handshakeTimeout, TimeUnit unit) {
575 checkNotNull(unit, "unit");
576 setHandshakeTimeoutMillis(unit.toMillis(handshakeTimeout));
577 }
578
579 public void setHandshakeTimeoutMillis(long handshakeTimeoutMillis) {
580 this.handshakeTimeoutMillis = checkPositiveOrZero(handshakeTimeoutMillis, "handshakeTimeoutMillis");
581 }
582
583 /**
584 * Sets the number of bytes to pass to each {@link SSLEngine#wrap(ByteBuffer[], int, int, ByteBuffer)} call.
585 * <p>
586 * This value will partition data which is passed to write
587 * {@link #write(ChannelHandlerContext, Object, ChannelPromise)}. The partitioning will work as follows:
588 * <ul>
589 * <li>If {@code wrapDataSize <= 0} then we will write each data chunk as is.</li>
590 * <li>If {@code wrapDataSize > data size} then we will attempt to aggregate multiple data chunks together.</li>
591 * <li>If {@code wrapDataSize > data size} Else if {@code wrapDataSize <= data size} then we will divide the data
592 * into chunks of {@code wrapDataSize} when writing.</li>
593 * </ul>
594 * <p>
595 * If the {@link SSLEngine} doesn't support a gather wrap operation (e.g. {@link SslProvider#OPENSSL}) then
596 * aggregating data before wrapping can help reduce the ratio between TLS overhead vs data payload which will lead
597 * to better goodput. Writing fixed chunks of data can also help target the underlying transport's (e.g. TCP)
598 * frame size. Under lossy/congested network conditions this may help the peer get full TLS packets earlier and
599 * be able to do work sooner, as opposed to waiting for the all the pieces of the TLS packet to arrive.
600 * @param wrapDataSize the number of bytes which will be passed to each
601 * {@link SSLEngine#wrap(ByteBuffer[], int, int, ByteBuffer)} call.
602 */
603 @UnstableApi
604 public final void setWrapDataSize(int wrapDataSize) {
605 this.wrapDataSize = wrapDataSize;
606 }
607
608 /**
609 * @deprecated use {@link #getCloseNotifyFlushTimeoutMillis()}
610 */
611 @Deprecated
612 public long getCloseNotifyTimeoutMillis() {
613 return getCloseNotifyFlushTimeoutMillis();
614 }
615
616 /**
617 * @deprecated use {@link #setCloseNotifyFlushTimeout(long, TimeUnit)}
618 */
619 @Deprecated
620 public void setCloseNotifyTimeout(long closeNotifyTimeout, TimeUnit unit) {
621 setCloseNotifyFlushTimeout(closeNotifyTimeout, unit);
622 }
623
624 /**
625 * @deprecated use {@link #setCloseNotifyFlushTimeoutMillis(long)}
626 */
627 @Deprecated
628 public void setCloseNotifyTimeoutMillis(long closeNotifyFlushTimeoutMillis) {
629 setCloseNotifyFlushTimeoutMillis(closeNotifyFlushTimeoutMillis);
630 }
631
632 /**
633 * Gets the timeout for flushing the close_notify that was triggered by closing the
634 * {@link Channel}. If the close_notify was not flushed in the given timeout the {@link Channel} will be closed
635 * forcibly.
636 */
637 public final long getCloseNotifyFlushTimeoutMillis() {
638 return closeNotifyFlushTimeoutMillis;
639 }
640
641 /**
642 * Sets the timeout for flushing the close_notify that was triggered by closing the
643 * {@link Channel}. If the close_notify was not flushed in the given timeout the {@link Channel} will be closed
644 * forcibly.
645 */
646 public final void setCloseNotifyFlushTimeout(long closeNotifyFlushTimeout, TimeUnit unit) {
647 setCloseNotifyFlushTimeoutMillis(unit.toMillis(closeNotifyFlushTimeout));
648 }
649
650 /**
651 * See {@link #setCloseNotifyFlushTimeout(long, TimeUnit)}.
652 */
653 public final void setCloseNotifyFlushTimeoutMillis(long closeNotifyFlushTimeoutMillis) {
654 this.closeNotifyFlushTimeoutMillis = checkPositiveOrZero(closeNotifyFlushTimeoutMillis,
655 "closeNotifyFlushTimeoutMillis");
656 }
657
658 /**
659 * Gets the timeout (in ms) for receiving the response for the close_notify that was triggered by closing the
660 * {@link Channel}. This timeout starts after the close_notify message was successfully written to the
661 * remote peer. Use {@code 0} to directly close the {@link Channel} and not wait for the response.
662 */
663 public final long getCloseNotifyReadTimeoutMillis() {
664 return closeNotifyReadTimeoutMillis;
665 }
666
667 /**
668 * Sets the timeout for receiving the response for the close_notify that was triggered by closing the
669 * {@link Channel}. This timeout starts after the close_notify message was successfully written to the
670 * remote peer. Use {@code 0} to directly close the {@link Channel} and not wait for the response.
671 */
672 public final void setCloseNotifyReadTimeout(long closeNotifyReadTimeout, TimeUnit unit) {
673 setCloseNotifyReadTimeoutMillis(unit.toMillis(closeNotifyReadTimeout));
674 }
675
676 /**
677 * See {@link #setCloseNotifyReadTimeout(long, TimeUnit)}.
678 */
679 public final void setCloseNotifyReadTimeoutMillis(long closeNotifyReadTimeoutMillis) {
680 this.closeNotifyReadTimeoutMillis = checkPositiveOrZero(closeNotifyReadTimeoutMillis,
681 "closeNotifyReadTimeoutMillis");
682 }
683
684 /**
685 * Returns the {@link SSLEngine} which is used by this handler.
686 */
687 public SSLEngine engine() {
688 return engine;
689 }
690
691 /**
692 * Returns the name of the current application-level protocol.
693 *
694 * @return the protocol name or {@code null} if application-level protocol has not been negotiated
695 */
696 public String applicationProtocol() {
697 SSLEngine engine = engine();
698 if (!(engine instanceof ApplicationProtocolAccessor)) {
699 return null;
700 }
701
702 return ((ApplicationProtocolAccessor) engine).getNegotiatedApplicationProtocol();
703 }
704
705 /**
706 * Returns a {@link Future} that will get notified once the current TLS handshake completes.
707 *
708 * @return the {@link Future} for the initial TLS handshake if {@link #renegotiate()} was not invoked.
709 * The {@link Future} for the most recent {@linkplain #renegotiate() TLS renegotiation} otherwise.
710 */
711 public Future<Channel> handshakeFuture() {
712 return handshakePromise;
713 }
714
715 /**
716 * Use {@link #closeOutbound()}
717 */
718 @Deprecated
719 public ChannelFuture close() {
720 return closeOutbound();
721 }
722
723 /**
724 * Use {@link #closeOutbound(ChannelPromise)}
725 */
726 @Deprecated
727 public ChannelFuture close(ChannelPromise promise) {
728 return closeOutbound(promise);
729 }
730
731 /**
732 * Sends an SSL {@code close_notify} message to the specified channel and
733 * destroys the underlying {@link SSLEngine}. This will <strong>not</strong> close the underlying
734 * {@link Channel}. If you want to also close the {@link Channel} use {@link Channel#close()} or
735 * {@link ChannelHandlerContext#close()}
736 */
737 public ChannelFuture closeOutbound() {
738 return closeOutbound(ctx.newPromise());
739 }
740
741 /**
742 * Sends an SSL {@code close_notify} message to the specified channel and
743 * destroys the underlying {@link SSLEngine}. This will <strong>not</strong> close the underlying
744 * {@link Channel}. If you want to also close the {@link Channel} use {@link Channel#close()} or
745 * {@link ChannelHandlerContext#close()}
746 */
747 public ChannelFuture closeOutbound(final ChannelPromise promise) {
748 final ChannelHandlerContext ctx = this.ctx;
749 if (ctx.executor().inEventLoop()) {
750 closeOutbound0(promise);
751 } else {
752 ctx.executor().execute(() -> closeOutbound0(promise));
753 }
754 return promise;
755 }
756
757 private void closeOutbound0(ChannelPromise promise) {
758 setState(STATE_OUTBOUND_CLOSED);
759 try {
760 closeOutboundAndFlush(ctx, promise, false);
761 } catch (Exception e) {
762 if (!promise.tryFailure(e)) {
763 logger.warn("{} flush() raised a masked exception.", ctx.channel(), e);
764 }
765 }
766 }
767
768 /**
769 * Return the {@link Future} that will get notified if the inbound of the {@link SSLEngine} is closed.
770 *
771 * This method will return the same {@link Future} all the time.
772 *
773 * @see SSLEngine
774 */
775 public Future<Channel> sslCloseFuture() {
776 return sslClosePromise;
777 }
778
779 @Override
780 public void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
781 try {
782 if (pendingUnencryptedWrites != null && !pendingUnencryptedWrites.isEmpty()) {
783 // Check if queue is not empty first because create a new ChannelException is expensive
784 pendingUnencryptedWrites.releaseAndFailAll(ctx,
785 new ChannelException("Pending write on removal of SslHandler"));
786 }
787 pendingUnencryptedWrites = null;
788 final ChannelPromise closeNotifyPromise = deferredCloseNotifyPromise;
789 if (closeNotifyPromise != null) {
790 deferredCloseNotifyPromise = null;
791 closeNotifyPromise.tryFailure(
792 new ChannelException("SslHandler removed before close_notify was written"));
793 }
794
795 SSLException cause = null;
796
797 // If the handshake or SSLEngine closure is not done yet we should fail corresponding promise and
798 // notify the rest of the
799 // pipeline.
800 if (!handshakePromise.isDone()) {
801 cause = new SSLHandshakeException("SslHandler removed before handshake completed");
802 if (handshakePromise.tryFailure(cause)) {
803 ctx.fireUserEventTriggered(new SslHandshakeCompletionEvent(cause));
804 }
805 }
806 if (!sslClosePromise.isDone()) {
807 if (cause == null) {
808 cause = new SSLException("SslHandler removed before SSLEngine was closed");
809 }
810 notifyClosePromise(cause);
811 }
812 } finally {
813 ReferenceCountUtil.release(engine);
814 }
815 }
816
817 @Override
818 public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
819 ctx.bind(localAddress, promise);
820 }
821
822 @Override
823 public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
824 ChannelPromise promise) throws Exception {
825 ctx.connect(remoteAddress, localAddress, promise);
826 }
827
828 @Override
829 public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
830 ctx.deregister(promise);
831 }
832
833 @Override
834 public void disconnect(final ChannelHandlerContext ctx,
835 final ChannelPromise promise) throws Exception {
836 closeOutboundAndChannel(ctx, promise, true);
837 }
838
839 @Override
840 public void close(final ChannelHandlerContext ctx,
841 final ChannelPromise promise) throws Exception {
842 closeOutboundAndChannel(ctx, promise, false);
843 }
844
845 @Override
846 public void read(ChannelHandlerContext ctx) throws Exception {
847 if (!handshakePromise.isDone()) {
848 setState(STATE_READ_DURING_HANDSHAKE);
849 }
850
851 ctx.read();
852 }
853
854 private static IllegalStateException newPendingWritesNullException() {
855 return new IllegalStateException("pendingUnencryptedWrites is null, handlerRemoved0 called?");
856 }
857
858 @Override
859 public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
860 if (!(msg instanceof ByteBuf)) {
861 UnsupportedMessageTypeException exception = new UnsupportedMessageTypeException(msg, ByteBuf.class);
862 ReferenceCountUtil.safeRelease(msg);
863 promise.setFailure(exception);
864 } else if (pendingUnencryptedWrites == null) {
865 ReferenceCountUtil.safeRelease(msg);
866 promise.setFailure(newPendingWritesNullException());
867 } else {
868 pendingUnencryptedWrites.add((ByteBuf) msg, promise);
869 }
870 }
871
872 @Override
873 public void flush(ChannelHandlerContext ctx) throws Exception {
874 // Do not encrypt the first write request if this handler is
875 // created with startTLS flag turned on.
876 if (startTls && !isStateSet(STATE_SENT_FIRST_MESSAGE)) {
877 setState(STATE_SENT_FIRST_MESSAGE);
878 pendingUnencryptedWrites.writeAndRemoveAll(ctx);
879 forceFlush(ctx);
880 // Explicit start handshake processing once we send the first message. This will also ensure
881 // we will schedule the timeout if needed.
882 startHandshakeProcessing(true);
883 return;
884 }
885
886 if (isStateSet(STATE_PROCESS_TASK)) {
887 return;
888 }
889
890 try {
891 wrapAndFlush(ctx);
892 } catch (Throwable cause) {
893 setHandshakeFailure(ctx, cause);
894 PlatformDependent.throwException(cause);
895 }
896 }
897
898 private void wrapAndFlush(ChannelHandlerContext ctx) throws SSLException {
899 if (pendingUnencryptedWrites.isEmpty()) {
900 // It's important to NOT use a voidPromise here as the user
901 // may want to add a ChannelFutureListener to the ChannelPromise later.
902 //
903 // See https://github.com/netty/netty/issues/3364
904 pendingUnencryptedWrites.add(Unpooled.EMPTY_BUFFER, ctx.newPromise());
905 }
906 if (!handshakePromise.isDone()) {
907 setState(STATE_FLUSHED_BEFORE_HANDSHAKE);
908 }
909 try {
910 wrap(ctx, false);
911 } finally {
912 // We may have written some parts of data before an exception was thrown so ensure we always flush.
913 // See https://github.com/netty/netty/issues/3900#issuecomment-172481830
914 forceFlush(ctx);
915 }
916 }
917
918 // This method will not call setHandshakeFailure(...) !
919 private void wrap(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException {
920 ByteBuf out = null;
921 ByteBufAllocator alloc = ctx.alloc();
922 try {
923 final int wrapDataSize = this.wrapDataSize;
924 // Only continue to loop if the handler was not removed in the meantime.
925 // See https://github.com/netty/netty/issues/5860
926 outer: while (!ctx.isRemoved() && !pendingUnencryptedWrites.isEmpty()) {
927 if (suspendWrapIfNeeded(ctx)) {
928 // We will resume once the encrypted data we wrote before was written by the transport.
929 break;
930 }
931 EncryptedWritePromise promise = new EncryptedWritePromise(ctx);
932 ByteBuf buf = wrapDataSize > 0 ?
933 pendingUnencryptedWrites.remove(alloc, wrapDataSize, promise) :
934 pendingUnencryptedWrites.removeFirst(promise);
935 if (buf == null) {
936 break;
937 }
938
939 SSLEngineResult result;
940
941 try {
942 if (buf.readableBytes() > MAX_PLAINTEXT_LENGTH) {
943 // If we pulled a buffer larger than the supported packet size, we can slice it up and
944 // iteratively, encrypting multiple packets into a single larger buffer. This substantially
945 // saves on allocations for large responses. Here we estimate how large of a buffer we need.
946 // If we overestimate a bit, that's fine. If we underestimate, we'll simply re-enqueue the
947 // remaining buffer and get it on the next outer loop.
948 int readableBytes = buf.readableBytes();
949 int numPackets = readableBytes / MAX_PLAINTEXT_LENGTH;
950 if (readableBytes % MAX_PLAINTEXT_LENGTH != 0) {
951 numPackets += 1;
952 }
953
954 if (out == null) {
955 out = allocateOutNetBuf(ctx, readableBytes, buf.nioBufferCount() + numPackets);
956 }
957 result = wrapMultiple(alloc, engine, buf, out);
958 } else {
959 if (out == null) {
960 out = allocateOutNetBuf(ctx, buf.readableBytes(), buf.nioBufferCount());
961 }
962 result = wrap(alloc, engine, buf, out);
963 }
964 } catch (Throwable e) {
965 // Either wrapMultiple(...), wrap(...) or allocateOutNetBuf(...) did throw.
966 // In this case we need to release the buffer that we removed from pendingUnencryptedWrites
967 // before failing the promise and rethrowing it. Failing to do so would result in a buffer leak.
968 // See https://github.com/netty/netty/issues/14644
969 //
970 // We don't need to release out here as this is done in a finally block already.
971 buf.release();
972 promise.setFailure(e);
973 throw e;
974 }
975
976 if (buf.isReadable()) {
977 pendingUnencryptedWrites.addFirst(buf, promise);
978 // When we add the buffer/promise pair back we need to be sure we don't complete the promise
979 // later. We only complete the promise if the buffer is completely consumed.
980 promise = null;
981 } else {
982 buf.release();
983 }
984
985 // We need to write any data before we invoke any methods which may trigger re-entry, otherwise
986 // writes may occur out of order and TLS sequencing may be off (e.g. SSLV3_ALERT_BAD_RECORD_MAC).
987 if (out.isReadable()) {
988 final ByteBuf b = out;
989 out = null;
990 if (promise == null) {
991 promise = new EncryptedWritePromise(ctx);
992 }
993 // Update the state before we write, as the write may trigger re-entry.
994 addPendingEncryptedWrite(promise, b.readableBytes());
995 ctx.write(b, promise);
996 } else if (promise != null) {
997 ctx.write(Unpooled.EMPTY_BUFFER, promise);
998 }
999 // else out is not readable we can re-use it and so save an extra allocation
1000
1001 if (result.getStatus() == Status.CLOSED) {
1002 // First check if there is any write left that needs to be failed, if there is none we don't need
1003 // to create a new exception or obtain an existing one.
1004 if (!pendingUnencryptedWrites.isEmpty()) {
1005 // Make a best effort to preserve any exception that way previously encountered from the
1006 // handshake or the transport, else fallback to a general error.
1007 Throwable exception = handshakePromise.cause();
1008 if (exception == null) {
1009 exception = sslClosePromise.cause();
1010 if (exception == null) {
1011 exception = new SslClosedEngineException("SSLEngine closed already");
1012 }
1013 }
1014 pendingUnencryptedWrites.releaseAndFailAll(ctx, exception);
1015 }
1016
1017 return;
1018 } else {
1019 switch (result.getHandshakeStatus()) {
1020 case NEED_TASK:
1021 if (!runDelegatedTasks(inUnwrap)) {
1022 // We scheduled a task on the delegatingTaskExecutor, so stop processing as we will
1023 // resume once the task completes.
1024 break outer;
1025 }
1026 break;
1027 case FINISHED:
1028 case NOT_HANDSHAKING: // work around for android bug that skips the FINISHED state.
1029 setHandshakeSuccess();
1030 break;
1031 case NEED_WRAP:
1032 // If we are expected to wrap again and we produced some data we need to ensure there
1033 // is something in the queue to process as otherwise we will not try again before there
1034 // was more added. Failing to do so may fail to produce an alert that can be
1035 // consumed by the remote peer.
1036 if (result.bytesProduced() > 0 && pendingUnencryptedWrites.isEmpty()) {
1037 pendingUnencryptedWrites.add(Unpooled.EMPTY_BUFFER);
1038 }
1039 break;
1040 case NEED_UNWRAP:
1041 // The underlying engine is starving so we need to feed it with more data.
1042 // See https://github.com/netty/netty/pull/5039
1043 readIfNeeded(ctx);
1044 return;
1045 default:
1046 throw new IllegalStateException(
1047 "Unknown handshake status: " + result.getHandshakeStatus());
1048 }
1049 }
1050 }
1051 } finally {
1052 if (out != null) {
1053 out.release();
1054 }
1055 if (inUnwrap) {
1056 setState(STATE_NEEDS_FLUSH);
1057 }
1058 if (pendingUnencryptedWrites == null || pendingUnencryptedWrites.isEmpty()) {
1059 clearState(STATE_WRAP_PENDING);
1060 }
1061 }
1062 }
1063
1064 /**
1065 * Returns {@code true} if we should stop wrapping application data for now, because more than
1066 * {@link ChannelConfig#getWriteBufferHighWaterMark()} bytes of the encrypted data we wrote before was not written
1067 * by the transport yet. This bounds the memory used for encrypted data that is waiting to be written.
1068 */
1069 private boolean suspendWrapIfNeeded(ChannelHandlerContext ctx) {
1070 if (isStateSet(STATE_WRAP_SUSPENDED)) {
1071 return true;
1072 }
1073 removeCompletedEncryptedWrites();
1074 // Once the outbound side is closed we need to wrap everything, as the SSLEngine would not wrap application
1075 // data anymore after closeOutbound() was called. Before the first message was sent with startTls, flush(...)
1076 // would write what we did not wrap unencrypted, so wrap everything in this case as well.
1077 if (pendingEncryptedBytes <= ctx.channel().config().getWriteBufferHighWaterMark() ||
1078 isStateSet(STATE_OUTBOUND_CLOSED) || startTls && !isStateSet(STATE_SENT_FIRST_MESSAGE)) {
1079 return false;
1080 }
1081 setState(STATE_WRAP_SUSPENDED | STATE_WRAP_PENDING);
1082 waitForPendingEncryptedWrite();
1083 return true;
1084 }
1085
1086 private void addPendingEncryptedWrite(EncryptedWritePromise promise, int bytes) {
1087 pendingEncryptedBytes += bytes;
1088 ArrayDeque<EncryptedWritePromise> writes = pendingEncryptedWrites;
1089 if (writes == null) {
1090 pendingEncryptedWrites = writes = new ArrayDeque<EncryptedWritePromise>();
1091 } else {
1092 EncryptedWritePromise last = writes.peekLast();
1093 if (last != null && !last.isDone() && last.bytes + bytes <= MAX_PLAINTEXT_LENGTH) {
1094 // Writes complete in order, so for small writes it is enough to wait for the last one. This keeps the
1095 // number of writes we track small.
1096 writes.pollLast();
1097 bytes += last.bytes;
1098 }
1099 }
1100 promise.bytes = bytes;
1101 writes.add(promise);
1102 }
1103
1104 private void removeCompletedEncryptedWrites() {
1105 final ArrayDeque<EncryptedWritePromise> writes = pendingEncryptedWrites;
1106 if (writes != null) {
1107 EncryptedWritePromise write;
1108 while ((write = writes.peekFirst()) != null && write.isDone()) {
1109 writes.pollFirst();
1110 pendingEncryptedBytes -= write.bytes;
1111 }
1112 }
1113 }
1114
1115 /**
1116 * Waits for the oldest of the writes of encrypted data that is not complete yet.
1117 */
1118 private void waitForPendingEncryptedWrite() {
1119 final ChannelFuture future = pendingEncryptedWrites.peekFirst();
1120 resumeWrapFuture = future;
1121 future.addListener(resumeWrapListener);
1122 }
1123
1124 private void resumeWrap(ChannelFuture future) {
1125 // Only resume if we are still waiting for this write. We may have resumed already, for example because the
1126 // outbound side was closed in the meantime.
1127 if (!isStateSet(STATE_WRAP_SUSPENDED) || future != resumeWrapFuture ||
1128 // Like flush(...) we must not wrap while a delegated task is running. We resume once it completed,
1129 // see delegatedTaskCompleted().
1130 isStateSet(STATE_PROCESS_TASK)) {
1131 return;
1132 }
1133 final ChannelHandlerContext ctx = this.ctx;
1134 // Let's check if the handler was removed in the meantime and so pendingUnencryptedWrites is null.
1135 if (pendingUnencryptedWrites != null && future.isSuccess()) {
1136 removeCompletedEncryptedWrites();
1137 if (pendingEncryptedBytes > ctx.channel().config().getWriteBufferLowWaterMark()) {
1138 // Like the writability of the Channel, continue only once we got to the low water mark.
1139 waitForPendingEncryptedWrite();
1140 return;
1141 }
1142 }
1143 clearState(STATE_WRAP_SUSPENDED);
1144 resumeWrapFuture = null;
1145 if (pendingUnencryptedWrites == null || pendingUnencryptedWrites.isEmpty()) {
1146 return;
1147 }
1148 if (!future.isSuccess()) {
1149 // The transport failed to write the encrypted data, so there is no point in encrypting what is left.
1150 releaseAndFailAll(ctx, future.cause());
1151 return;
1152 }
1153 try {
1154 flush(ctx);
1155 } catch (Throwable cause) {
1156 // Do the same as the ChannelPipeline would do if flush(...) throws.
1157 try {
1158 exceptionCaught(ctx, cause);
1159 } catch (Throwable error) {
1160 ctx.fireExceptionCaught(error);
1161 }
1162 }
1163 }
1164
1165 /**
1166 * Closes the outbound side of the {@link SSLEngine} and flushes, which writes the {@code close_notify} and
1167 * notifies {@code promise} once it is written. If wrapping was suspended, the data that is still queued is wrapped
1168 * first, as the {@link SSLEngine} would not wrap it anymore once its outbound side is closed.
1169 *
1170 * @param deferred {@code true} if this is called once the delegated task we had to wait for completed.
1171 */
1172 private void closeOutboundAndFlush(ChannelHandlerContext ctx, ChannelPromise promise, boolean deferred)
1173 throws Exception {
1174 assert isStateSet(STATE_OUTBOUND_CLOSED);
1175 final boolean wrapPending = deferred || isStateSet(STATE_WRAP_SUSPENDED) || isStateSet(STATE_WRAP_PENDING) ||
1176 deferredCloseNotifyPromise != null;
1177 if (wrapPending && pendingUnencryptedWrites != null && ctx.channel().isActive()) {
1178 if (!isStateSet(STATE_PROCESS_TASK)) {
1179 clearState(STATE_WRAP_SUSPENDED);
1180 try {
1181 int readableBytes;
1182 do {
1183 readableBytes = pendingUnencryptedWrites.readableBytes();
1184 // As STATE_OUTBOUND_CLOSED is set this will not suspend again. It returns after each record
1185 // while the engine is handshaking though, so call it as long as it makes progress.
1186 wrap(ctx, false);
1187 } while (pendingUnencryptedWrites != null && !pendingUnencryptedWrites.isEmpty() &&
1188 !isStateSet(STATE_PROCESS_TASK) &&
1189 pendingUnencryptedWrites.readableBytes() < readableBytes);
1190 } catch (Throwable cause) {
1191 setHandshakeFailure(ctx, cause);
1192 }
1193 }
1194 if (isStateSet(STATE_PROCESS_TASK)) {
1195 // We must not wrap while a delegated task is running, so continue once it completed.
1196 // See delegatedTaskCompleted().
1197 if (deferredCloseNotifyPromise == null) {
1198 deferredCloseNotifyPromise = promise;
1199 } else {
1200 PromiseNotifier.cascade(false, deferredCloseNotifyPromise, promise);
1201 }
1202 return;
1203 }
1204 }
1205 clearState(STATE_WRAP_SUSPENDED);
1206 engine.closeOutbound();
1207 flush(ctx, promise);
1208 }
1209
1210 /**
1211 * Called on the {@link EventExecutor} once a delegated task completed, to do what had to wait for it.
1212 */
1213 private void delegatedTaskCompleted() {
1214 if (isStateSet(STATE_PROCESS_TASK)) {
1215 // Another task was started in the meantime, we will be called again once it completed.
1216 return;
1217 }
1218 final ChannelPromise promise = deferredCloseNotifyPromise;
1219 if (promise != null) {
1220 deferredCloseNotifyPromise = null;
1221 try {
1222 closeOutboundAndFlush(ctx, promise, true);
1223 } catch (Throwable cause) {
1224 promise.tryFailure(cause);
1225 }
1226 } else if (isStateSet(STATE_WRAP_SUSPENDED) && resumeWrapFuture.isDone()) {
1227 // The write we waited for completed while the task was running, so we could not resume back then.
1228 resumeWrap(resumeWrapFuture);
1229 }
1230 }
1231
1232 /**
1233 * Called once a delegated task that was run directly completed. As we are wrapping or unwrapping then, what had
1234 * to wait for the task is done later on the {@link EventExecutor}.
1235 */
1236 private void directDelegatedTaskCompleted() {
1237 if (deferredCloseNotifyPromise != null || isStateSet(STATE_WRAP_SUSPENDED) && resumeWrapFuture.isDone()) {
1238 try {
1239 ctx.executor().execute(this::delegatedTaskCompleted);
1240 } catch (RejectedExecutionException ignore) {
1241 // The executor is shutting down, which closes the channel and so fails what is pending.
1242 }
1243 }
1244 }
1245
1246 /**
1247 * This method will not call
1248 * {@link #setHandshakeFailure(ChannelHandlerContext, Throwable, boolean, boolean, boolean)} or
1249 * {@link #setHandshakeFailure(ChannelHandlerContext, Throwable)}.
1250 * @return {@code true} if this method ends on {@link SSLEngineResult.HandshakeStatus#NOT_HANDSHAKING}.
1251 */
1252 private boolean wrapNonAppData(final ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException {
1253 ByteBuf out = null;
1254 ByteBufAllocator alloc = ctx.alloc();
1255 try {
1256 // Only continue to loop if the handler was not removed in the meantime.
1257 // See https://github.com/netty/netty/issues/5860
1258 outer: while (!ctx.isRemoved()) {
1259 if (out == null) {
1260 // As this is called for the handshake we have no real idea how big the buffer needs to be.
1261 // That said 2048 should give us enough room to include everything like ALPN / NPN data.
1262 // If this is not enough we will increase the buffer in wrap(...).
1263 out = allocateOutNetBuf(ctx, 2048, 1);
1264 }
1265 SSLEngineResult result = wrap(alloc, engine, Unpooled.EMPTY_BUFFER, out);
1266 if (result.bytesProduced() > 0) {
1267 ctx.write(out).addListener(future -> {
1268 Throwable cause = future.cause();
1269 if (cause != null) {
1270 setHandshakeFailureTransportFailure(ctx, cause);
1271 }
1272 });
1273 if (inUnwrap) {
1274 setState(STATE_NEEDS_FLUSH);
1275 }
1276 out = null;
1277 }
1278
1279 HandshakeStatus status = result.getHandshakeStatus();
1280 switch (status) {
1281 case FINISHED:
1282 // We may be here because we read data and discovered the remote peer initiated a renegotiation
1283 // and this write is to complete the new handshake. The user may have previously done a
1284 // writeAndFlush which wasn't able to wrap data due to needing the pending handshake, so we
1285 // attempt to wrap application data here if any is pending.
1286 if (setHandshakeSuccess() && inUnwrap && !pendingUnencryptedWrites.isEmpty()) {
1287 wrap(ctx, true);
1288 }
1289 return false;
1290 case NEED_TASK:
1291 if (!runDelegatedTasks(inUnwrap)) {
1292 // We scheduled a task on the delegatingTaskExecutor, so stop processing as we will
1293 // resume once the task completes.
1294 break outer;
1295 }
1296 break;
1297 case NEED_UNWRAP:
1298 if (inUnwrap || unwrapNonAppData(ctx) <= 0) {
1299 // If we asked for a wrap, the engine requested an unwrap, and we are in unwrap there is
1300 // no use in trying to call wrap again because we have already attempted (or will after we
1301 // return) to feed more data to the engine.
1302 return false;
1303 }
1304 break;
1305 case NEED_WRAP:
1306 break;
1307 case NOT_HANDSHAKING:
1308 if (setHandshakeSuccess() && inUnwrap && !pendingUnencryptedWrites.isEmpty()) {
1309 wrap(ctx, true);
1310 }
1311 // Workaround for TLS False Start problem reported at:
1312 // https://github.com/netty/netty/issues/1108#issuecomment-14266970
1313 if (!inUnwrap) {
1314 unwrapNonAppData(ctx);
1315 }
1316 return true;
1317 default:
1318 throw new IllegalStateException("Unknown handshake status: " + result.getHandshakeStatus());
1319 }
1320
1321 // Check if did not produce any bytes and if so break out of the loop, but only if we did not process
1322 // a task as last action. It's fine to not produce any data as part of executing a task.
1323 if (result.bytesProduced() == 0 && status != HandshakeStatus.NEED_TASK) {
1324 break;
1325 }
1326 }
1327 } finally {
1328 if (out != null) {
1329 out.release();
1330 }
1331 }
1332 return false;
1333 }
1334
1335 private SSLEngineResult wrapMultiple(ByteBufAllocator alloc, SSLEngine engine, ByteBuf in, ByteBuf out)
1336 throws SSLException {
1337 SSLEngineResult result = null;
1338
1339 do {
1340 int nextSliceSize = Math.min(MAX_PLAINTEXT_LENGTH, in.readableBytes());
1341 // This call over-estimates, because we are slicing and not every nioBuffer will be part of
1342 // every slice. We could improve the estimate by having an nioBufferCount(offset, length).
1343 int nextOutSize = engineType.calculateRequiredOutBufSpace(this, nextSliceSize, in.nioBufferCount());
1344
1345 if (!out.isWritable(nextOutSize)) {
1346 if (result != null) {
1347 // We underestimated the space needed to encrypt the entire in buf. Break out, and
1348 // upstream will re-enqueue the buffer for later.
1349 break;
1350 }
1351 // This shouldn't happen, as the out buf was properly sized for at least packetLength
1352 // prior to calling wrap.
1353 out.ensureWritable(nextOutSize);
1354 }
1355
1356 ByteBuf wrapBuf = in.readSlice(nextSliceSize);
1357 result = wrap(alloc, engine, wrapBuf, out);
1358
1359 if (result.getStatus() == Status.CLOSED) {
1360 // If the engine gets closed, we can exit out early. Otherwise, we'll do a full handling of
1361 // possible results once finished.
1362 break;
1363 }
1364
1365 if (wrapBuf.isReadable()) {
1366 // There may be some left-over, in which case we can just pick it up next loop, so reset the original
1367 // reader index so its included again in the next slice.
1368 in.readerIndex(in.readerIndex() - wrapBuf.readableBytes());
1369 }
1370
1371 if (result.bytesConsumed() == 0 && result.bytesProduced() == 0) {
1372 // The engine did neither consume nor produce anything, for example because the handshake is not done
1373 // yet. Break out so the caller handles the handshake status, as otherwise we would loop forever.
1374 break;
1375 }
1376 } while (in.readableBytes() > 0);
1377
1378 return result;
1379 }
1380
1381 private SSLEngineResult wrap(ByteBufAllocator alloc, SSLEngine engine, ByteBuf in, ByteBuf out)
1382 throws SSLException {
1383 ByteBuf newDirectIn = null;
1384 try {
1385 int readerIndex = in.readerIndex();
1386 int readableBytes = in.readableBytes();
1387
1388 // We will call SslEngine.wrap(ByteBuffer[], ByteBuffer) to allow efficient handling of
1389 // CompositeByteBuf without force an extra memory copy when CompositeByteBuffer.nioBuffer() is called.
1390 final ByteBuffer[] in0;
1391 if (in.isDirect() || !engineType.wantsDirectBuffer) {
1392 // As CompositeByteBuf.nioBufferCount() can be expensive (as it needs to check all composed ByteBuf
1393 // to calculate the count) we will just assume a CompositeByteBuf contains more then 1 ByteBuf.
1394 // The worst that can happen is that we allocate an extra ByteBuffer[] in CompositeByteBuf.nioBuffers()
1395 // which is better then walking the composed ByteBuf in most cases.
1396 if (!(in instanceof CompositeByteBuf) && in.nioBufferCount() == 1) {
1397 in0 = singleBuffer;
1398 // We know its only backed by 1 ByteBuffer so use internalNioBuffer to keep object allocation
1399 // to a minimum.
1400 in0[0] = in.internalNioBuffer(readerIndex, readableBytes);
1401 } else {
1402 in0 = in.nioBuffers();
1403 }
1404 } else {
1405 // We could even go further here and check if its a CompositeByteBuf and if so try to decompose it and
1406 // only replace the ByteBuffer that are not direct. At the moment we just will replace the whole
1407 // CompositeByteBuf to keep the complexity to a minimum
1408 newDirectIn = alloc.directBuffer(readableBytes);
1409 newDirectIn.writeBytes(in, readerIndex, readableBytes);
1410 in0 = singleBuffer;
1411 in0[0] = newDirectIn.internalNioBuffer(newDirectIn.readerIndex(), readableBytes);
1412 }
1413
1414 for (;;) {
1415 // Use toByteBuffer(...) which might be able to return the internal ByteBuffer and so reduce
1416 // allocations.
1417 ByteBuffer out0 = toByteBuffer(out, out.writerIndex(), out.writableBytes());
1418 SSLEngineResult result = engine.wrap(in0, out0);
1419 in.skipBytes(result.bytesConsumed());
1420 out.writerIndex(out.writerIndex() + result.bytesProduced());
1421
1422 if (result.getStatus() == Status.BUFFER_OVERFLOW) {
1423 out.ensureWritable(engine.getSession().getPacketBufferSize());
1424 } else {
1425 return result;
1426 }
1427 }
1428 } finally {
1429 // Null out to allow GC of ByteBuffer
1430 singleBuffer[0] = null;
1431
1432 if (newDirectIn != null) {
1433 newDirectIn.release();
1434 }
1435 }
1436 }
1437
1438 @Override
1439 public void channelInactive(ChannelHandlerContext ctx) throws Exception {
1440 boolean handshakeFailed = handshakePromise.cause() != null;
1441
1442 // Channel closed, we will generate 'ClosedChannelException' now.
1443 StacklessClosedChannelException exception = StacklessClosedChannelException.newInstance(
1444 SslHandler.class, "channelInactive(ChannelHandlerContext)");
1445
1446 // Add a suppressed exception if the handshake was not completed yet.
1447 if (isStateSet(STATE_HANDSHAKE_STARTED) && !handshakePromise.isDone()) {
1448 ThrowableUtil.addSuppressed(exception, StacklessSSLHandshakeException.newInstance(
1449 "Connection closed while SSL/TLS handshake was in progress",
1450 SslHandler.class, "channelInactive"));
1451 }
1452
1453 // Make sure to release SSLEngine,
1454 // and notify the handshake future if the connection has been closed during handshake.
1455 setHandshakeFailure(ctx, exception, !isStateSet(STATE_OUTBOUND_CLOSED), isStateSet(STATE_HANDSHAKE_STARTED),
1456 false);
1457
1458 // Ensure we always notify the sslClosePromise as well
1459 notifyClosePromise(exception);
1460
1461 try {
1462 super.channelInactive(ctx);
1463 } catch (DecoderException e) {
1464 if (!handshakeFailed || !(e.getCause() instanceof SSLException)) {
1465 // We only rethrow the exception if the handshake did not fail before channelInactive(...) was called
1466 // as otherwise this may produce duplicated failures as super.channelInactive(...) will also call
1467 // channelRead(...).
1468 //
1469 // See https://github.com/netty/netty/issues/10119
1470 throw e;
1471 }
1472 }
1473 }
1474
1475 @Override
1476 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
1477 if (ignoreException(cause)) {
1478 // It is safe to ignore the 'connection reset by peer' or
1479 // 'broken pipe' error after sending close_notify.
1480 if (logger.isDebugEnabled()) {
1481 logger.debug(
1482 "{} Swallowing a harmless 'connection reset by peer / broken pipe' error that occurred " +
1483 "while writing close_notify in response to the peer's close_notify", ctx.channel(), cause);
1484 }
1485
1486 // Close the connection explicitly just in case the transport
1487 // did not close the connection automatically.
1488 if (ctx.channel().isActive()) {
1489 ctx.close();
1490 }
1491 } else {
1492 ctx.fireExceptionCaught(cause);
1493 }
1494 }
1495
1496 /**
1497 * Checks if the given {@link Throwable} can be ignore and just "swallowed"
1498 *
1499 * When an ssl connection is closed a close_notify message is sent.
1500 * After that the peer also sends close_notify however, it's not mandatory to receive
1501 * the close_notify. The party who sent the initial close_notify can close the connection immediately
1502 * then the peer will get connection reset error.
1503 *
1504 */
1505 private boolean ignoreException(Throwable t) {
1506 if (!(t instanceof SSLException) && t instanceof IOException && sslClosePromise.isDone()) {
1507 String message = t.getMessage();
1508
1509 // first try to match connection reset / broke peer based on the regex. This is the fastest way
1510 // but may fail on different jdk impls or OS's
1511 if (message != null && IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) {
1512 return true;
1513 }
1514
1515 // Inspect the StackTraceElements to see if it was a connection reset / broken pipe or not
1516 StackTraceElement[] elements = t.getStackTrace();
1517 for (StackTraceElement element: elements) {
1518 String classname = element.getClassName();
1519 String methodname = element.getMethodName();
1520
1521 // skip all classes that belong to the io.netty package
1522 if (classname.startsWith("io.netty.")) {
1523 continue;
1524 }
1525
1526 // check if the method name is read if not skip it
1527 if (!"read".equals(methodname)) {
1528 continue;
1529 }
1530
1531 if (isIgnorableClassInStack(classname)) {
1532 return true;
1533 }
1534
1535 try {
1536 // No match by now. Try to load the class via classloader and inspect it.
1537 // This is mainly done as other JDK implementations may differ in name of
1538 // the impl.
1539 Class<?> clazz = PlatformDependent.getClassLoader(getClass()).loadClass(classname);
1540
1541 if (SocketChannel.class.isAssignableFrom(clazz)
1542 || DatagramChannel.class.isAssignableFrom(clazz)) {
1543 return true;
1544 }
1545
1546 // also match against SctpChannel via String matching as it may not present.
1547 if ("com.sun.nio.sctp.SctpChannel".equals(clazz.getSuperclass().getName())) {
1548 return true;
1549 }
1550 } catch (Throwable cause) {
1551 if (logger.isDebugEnabled()) {
1552 logger.debug("Unexpected exception while loading class {} classname {}",
1553 getClass(), classname, cause);
1554 }
1555 }
1556 }
1557 }
1558
1559 return false;
1560 }
1561
1562 private static boolean isIgnorableClassInStack(String classname) {
1563 return classname.contains("SocketChannel") ||
1564 classname.contains("DatagramChannel") ||
1565 classname.contains("SctpChannel") ||
1566 classname.contains("UdtChannel");
1567 }
1568
1569 /**
1570 * Returns {@code true} if the given {@link ByteBuf} is encrypted. Be aware that this method
1571 * will not increase the readerIndex of the given {@link ByteBuf}.
1572 *
1573 * @param buffer
1574 * The {@link ByteBuf} to read from. Be aware that it must have at least 5 bytes to read,
1575 * otherwise it will throw an {@link IllegalArgumentException}.
1576 * @return encrypted
1577 * {@code true} if the {@link ByteBuf} is encrypted, {@code false} otherwise.
1578 * @throws IllegalArgumentException
1579 * Is thrown if the given {@link ByteBuf} has not at least 5 bytes to read.
1580 * @deprecated use {@link #isEncrypted(ByteBuf, boolean)}.
1581 */
1582 @Deprecated
1583 public static boolean isEncrypted(ByteBuf buffer) {
1584 return isEncrypted(buffer, false);
1585 }
1586
1587 /**
1588 * Returns {@code true} if the given {@link ByteBuf} is encrypted. Be aware that this method
1589 * will not increase the readerIndex of the given {@link ByteBuf}.
1590 *
1591 * @param buffer
1592 * The {@link ByteBuf} to read from. Be aware that it must have at least 5 bytes to read,
1593 * otherwise it will throw an {@link IllegalArgumentException}.
1594 * @return encrypted
1595 * {@code true} if the {@link ByteBuf} is encrypted, {@code false} otherwise.
1596 * @param probeSSLv2
1597 * {@code true} if the input {@code buffer} might be SSLv2. If {@code true} is used this
1598 * methods might produce false-positives in some cases so it's strongly suggested to
1599 * use {@code false}.
1600 * @throws IllegalArgumentException
1601 * Is thrown if the given {@link ByteBuf} has not at least 5 bytes to read.
1602 */
1603 public static boolean isEncrypted(ByteBuf buffer, boolean probeSSLv2) {
1604 if (buffer.readableBytes() < SslUtils.SSL_RECORD_HEADER_LENGTH) {
1605 throw new IllegalArgumentException(
1606 "buffer must have at least " + SslUtils.SSL_RECORD_HEADER_LENGTH + " readable bytes");
1607 }
1608 return getEncryptedPacketLength(buffer, buffer.readerIndex(), probeSSLv2) != SslUtils.NOT_ENCRYPTED;
1609 }
1610
1611 private void decodeJdkCompatible(ChannelHandlerContext ctx, ByteBuf in) throws NotSslRecordException {
1612 int packetLength = this.packetLength;
1613 // If we calculated the length of the current SSL record before, use that information.
1614 if (packetLength > 0) {
1615 if (in.readableBytes() < packetLength) {
1616 return;
1617 }
1618 } else {
1619 // Get the packet length and wait until we get a packets worth of data to unwrap.
1620 final int readableBytes = in.readableBytes();
1621 if (readableBytes < SslUtils.SSL_RECORD_HEADER_LENGTH) {
1622 return;
1623 }
1624 packetLength = getEncryptedPacketLength(in, in.readerIndex(), true);
1625 if (packetLength == SslUtils.NOT_ENCRYPTED) {
1626 // Not an SSL/TLS packet
1627 NotSslRecordException e = new NotSslRecordException(
1628 "not an SSL/TLS record: " + ByteBufUtil.hexDump(in));
1629 in.skipBytes(in.readableBytes());
1630
1631 // First fail the handshake promise as we may need to have access to the SSLEngine which may
1632 // be released because the user will remove the SslHandler in an exceptionCaught(...) implementation.
1633 setHandshakeFailure(ctx, e);
1634
1635 throw e;
1636 }
1637 if (packetLength == NOT_ENOUGH_DATA) {
1638 return;
1639 }
1640 assert packetLength > 0;
1641 if (packetLength > readableBytes) {
1642 // wait until the whole packet can be read
1643 this.packetLength = packetLength;
1644 return;
1645 }
1646 }
1647
1648 // Reset the state of this class so we can get the length of the next packet. We assume the entire packet will
1649 // be consumed by the SSLEngine.
1650 this.packetLength = 0;
1651 try {
1652 final int bytesConsumed = unwrap(ctx, in, packetLength);
1653 if (bytesConsumed != packetLength && !engine.isInboundDone()) {
1654 // The JDK equivalent of getEncryptedPacketLength has some optimizations and can behave slightly
1655 // differently to ours, but this should always be a sign of bad input data.
1656 throw new NotSslRecordException();
1657 }
1658 } catch (Throwable cause) {
1659 handleUnwrapThrowable(ctx, cause);
1660 }
1661 }
1662
1663 private void decodeNonJdkCompatible(ChannelHandlerContext ctx, ByteBuf in) {
1664 try {
1665 unwrap(ctx, in, in.readableBytes());
1666 } catch (Throwable cause) {
1667 handleUnwrapThrowable(ctx, cause);
1668 }
1669 }
1670
1671 private void handleUnwrapThrowable(ChannelHandlerContext ctx, Throwable cause) {
1672 try {
1673 // We should attempt to notify the handshake failure before writing any pending data. If we are in unwrap
1674 // and failed during the handshake process, and we attempt to wrap, then promises will fail, and if
1675 // listeners immediately close the Channel then we may end up firing the handshake event after the Channel
1676 // has been closed.
1677 if (handshakePromise.tryFailure(cause)) {
1678 ctx.fireUserEventTriggered(new SslHandshakeCompletionEvent(cause));
1679 }
1680
1681 // Let's check if the handler was removed in the meantime and so pendingUnencryptedWrites is null.
1682 if (pendingUnencryptedWrites != null) {
1683 // Don't wait for previous writes to complete, as the alert should be sent now. The outbound side is
1684 // closed below anyway, and setting STATE_OUTBOUND_CLOSED makes sure that wrapping is not suspended.
1685 clearState(STATE_WRAP_SUSPENDED);
1686 setState(STATE_OUTBOUND_CLOSED);
1687 // We need to flush one time as there may be an alert that we should send to the remote peer because
1688 // of the SSLException reported here.
1689 wrapAndFlush(ctx);
1690 }
1691 } catch (SSLException ex) {
1692 logger.debug("SSLException during trying to call SSLEngine.wrap(...)" +
1693 " because of an previous SSLException, ignoring...", ex);
1694 } finally {
1695 // ensure we always flush and close the channel.
1696 setHandshakeFailure(ctx, cause, true, false, true);
1697 }
1698 PlatformDependent.throwException(cause);
1699 }
1700
1701 @Override
1702 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws SSLException {
1703 if (isStateSet(STATE_PROCESS_TASK)) {
1704 return;
1705 }
1706 if (jdkCompatibilityMode) {
1707 decodeJdkCompatible(ctx, in);
1708 } else {
1709 decodeNonJdkCompatible(ctx, in);
1710 }
1711 }
1712
1713 @Override
1714 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
1715 channelReadComplete0(ctx);
1716 }
1717
1718 private void channelReadComplete0(ChannelHandlerContext ctx) {
1719 // Discard bytes of the cumulation buffer if needed.
1720 discardSomeReadBytes();
1721
1722 flushIfNeeded(ctx);
1723 readIfNeeded(ctx);
1724
1725 clearState(STATE_FIRE_CHANNEL_READ);
1726 ctx.fireChannelReadComplete();
1727 }
1728
1729 private void readIfNeeded(ChannelHandlerContext ctx) {
1730 // If handshake is not finished yet, we need more data.
1731 if (!ctx.channel().config().isAutoRead() &&
1732 (!isStateSet(STATE_FIRE_CHANNEL_READ) || !handshakePromise.isDone())) {
1733 // No auto-read used and no message passed through the ChannelPipeline or the handshake was not complete
1734 // yet, which means we need to trigger the read to ensure we not encounter any stalls.
1735 ctx.read();
1736 }
1737 }
1738
1739 private void flushIfNeeded(ChannelHandlerContext ctx) {
1740 if (isStateSet(STATE_NEEDS_FLUSH)) {
1741 forceFlush(ctx);
1742 }
1743 }
1744
1745 /**
1746 * Calls {@link SSLEngine#unwrap(ByteBuffer, ByteBuffer)} with an empty buffer to handle handshakes, etc.
1747 */
1748 private int unwrapNonAppData(ChannelHandlerContext ctx) throws SSLException {
1749 return unwrap(ctx, Unpooled.EMPTY_BUFFER, 0);
1750 }
1751
1752 /**
1753 * Unwraps inbound SSL records.
1754 */
1755 private int unwrap(ChannelHandlerContext ctx, ByteBuf packet, int length) throws SSLException {
1756 final int originalLength = length;
1757 boolean wrapLater = false;
1758 boolean notifyClosure = false;
1759 boolean executedRead = false;
1760 ByteBuf decodeOut = allocate(ctx, engineType.calculateInitialUnwrapBufSize(this, length));
1761 try {
1762 // Only continue to loop if the handler was not removed in the meantime.
1763 // See https://github.com/netty/netty/issues/5860
1764 do {
1765 final SSLEngineResult result = engineType.unwrap(this, packet, length, decodeOut);
1766 final Status status = result.getStatus();
1767 final HandshakeStatus handshakeStatus = result.getHandshakeStatus();
1768 final int produced = result.bytesProduced();
1769 final int consumed = result.bytesConsumed();
1770
1771 // Skip bytes now in case unwrap is called in a re-entry scenario. For example LocalChannel.read()
1772 // may entry this method in a re-entry fashion and if the peer is writing into a shared buffer we may
1773 // unwrap the same data multiple times.
1774 packet.skipBytes(consumed);
1775 length -= consumed;
1776
1777 // The expected sequence of events is:
1778 // 1. Notify of handshake success
1779 // 2. fireChannelRead for unwrapped data
1780 if (handshakeStatus == HandshakeStatus.FINISHED || handshakeStatus == HandshakeStatus.NOT_HANDSHAKING) {
1781 wrapLater |= (decodeOut.isReadable() ?
1782 setHandshakeSuccessUnwrapMarkReentry() : setHandshakeSuccess()) ||
1783 handshakeStatus == HandshakeStatus.FINISHED ||
1784 // We need to check if pendingUnecryptedWrites is null as the SslHandler
1785 // might have been removed in the meantime.
1786 (pendingUnencryptedWrites != null && !pendingUnencryptedWrites.isEmpty());
1787 }
1788
1789 // Dispatch decoded data after we have notified of handshake success. If this method has been invoked
1790 // in a re-entry fashion we execute a task on the executor queue to process after the stack unwinds
1791 // to preserve order of events.
1792 if (decodeOut.isReadable()) {
1793 setState(STATE_FIRE_CHANNEL_READ);
1794 if (isStateSet(STATE_UNWRAP_REENTRY)) {
1795 executedRead = true;
1796 executeChannelRead(ctx, decodeOut);
1797 } else {
1798 ctx.fireChannelRead(decodeOut);
1799 }
1800 decodeOut = null;
1801 }
1802
1803 if (status == Status.CLOSED) {
1804 notifyClosure = true; // notify about the CLOSED state of the SSLEngine. See #137
1805 } else if (status == Status.BUFFER_OVERFLOW) {
1806 if (decodeOut != null) {
1807 decodeOut.release();
1808 }
1809 final int applicationBufferSize = engine.getSession().getApplicationBufferSize();
1810 // Allocate a new buffer which can hold all the rest data and loop again.
1811 // It may happen that applicationBufferSize < produced while there is still more to unwrap, in this
1812 // case we will just allocate a new buffer with the capacity of applicationBufferSize and call
1813 // unwrap again.
1814 decodeOut = allocate(ctx, engineType.calculatePendingData(this, applicationBufferSize < produced ?
1815 applicationBufferSize : applicationBufferSize - produced));
1816 continue;
1817 }
1818
1819 if (handshakeStatus == HandshakeStatus.NEED_TASK) {
1820 boolean pending = runDelegatedTasks(true);
1821 if (!pending) {
1822 // We scheduled a task on the delegatingTaskExecutor, so stop processing as we will
1823 // resume once the task completes.
1824 //
1825 // We break out of the loop only and do NOT return here as we still may need to notify
1826 // about the closure of the SSLEngine.
1827 wrapLater = false;
1828 break;
1829 }
1830 } else if (handshakeStatus == HandshakeStatus.NEED_WRAP) {
1831 // If the wrap operation transitions the status to NOT_HANDSHAKING and there is no more data to
1832 // unwrap then the next call to unwrap will not produce any data. We can avoid the potentially
1833 // costly unwrap operation and break out of the loop.
1834 if (wrapNonAppData(ctx, true) && length == 0) {
1835 break;
1836 }
1837 }
1838
1839 if (status == Status.BUFFER_UNDERFLOW ||
1840 // If we processed NEED_TASK we should try again even we did not consume or produce anything.
1841 handshakeStatus != HandshakeStatus.NEED_TASK && (consumed == 0 && produced == 0 ||
1842 (length == 0 && handshakeStatus == HandshakeStatus.NOT_HANDSHAKING))) {
1843 if (handshakeStatus == HandshakeStatus.NEED_UNWRAP) {
1844 // The underlying engine is starving so we need to feed it with more data.
1845 // See https://github.com/netty/netty/pull/5039
1846 readIfNeeded(ctx);
1847 }
1848
1849 break;
1850 } else if (decodeOut == null) {
1851 decodeOut = allocate(ctx, engineType.calculateInitialUnwrapBufSize(this, length));
1852 }
1853 } while (!ctx.isRemoved());
1854
1855 if (isStateSet(STATE_FLUSHED_BEFORE_HANDSHAKE) && handshakePromise.isDone()) {
1856 // We need to call wrap(...) in case there was a flush done before the handshake completed to ensure
1857 // we do not stale.
1858 //
1859 // See https://github.com/netty/netty/pull/2437
1860 clearState(STATE_FLUSHED_BEFORE_HANDSHAKE);
1861 wrapLater = true;
1862 }
1863
1864 if (wrapLater) {
1865 wrap(ctx, true);
1866 }
1867 } finally {
1868 if (decodeOut != null) {
1869 decodeOut.release();
1870 }
1871
1872 if (notifyClosure) {
1873 if (executedRead) {
1874 executeNotifyClosePromise(ctx);
1875 } else {
1876 notifyClosePromise(null);
1877 }
1878 }
1879 }
1880 return originalLength - length;
1881 }
1882
1883 private boolean setHandshakeSuccessUnwrapMarkReentry() throws SSLException {
1884 // setHandshakeSuccess calls out to external methods which may trigger re-entry. We need to preserve ordering of
1885 // fireChannelRead for decodeOut relative to re-entry data.
1886 final boolean setReentryState = !isStateSet(STATE_UNWRAP_REENTRY);
1887 if (setReentryState) {
1888 setState(STATE_UNWRAP_REENTRY);
1889 }
1890 try {
1891 return setHandshakeSuccess();
1892 } finally {
1893 // It is unlikely this specific method will be re-entry because handshake completion is infrequent, but just
1894 // in case we only clear the state if we set it in the first place.
1895 if (setReentryState) {
1896 clearState(STATE_UNWRAP_REENTRY);
1897 }
1898 }
1899 }
1900
1901 private void executeNotifyClosePromise(final ChannelHandlerContext ctx) {
1902 try {
1903 ctx.executor().execute(() -> notifyClosePromise(null));
1904 } catch (RejectedExecutionException e) {
1905 notifyClosePromise(e);
1906 }
1907 }
1908
1909 private void executeChannelRead(final ChannelHandlerContext ctx, final ByteBuf decodedOut) {
1910 try {
1911 ctx.executor().execute(() -> ctx.fireChannelRead(decodedOut));
1912 } catch (RejectedExecutionException e) {
1913 decodedOut.release();
1914 throw e;
1915 }
1916 }
1917
1918 private static ByteBuffer toByteBuffer(ByteBuf out, int index, int len) {
1919 return out.nioBufferCount() == 1 ? out.internalNioBuffer(index, len) :
1920 out.nioBuffer(index, len);
1921 }
1922
1923 private static boolean inEventLoop(Executor executor) {
1924 return executor instanceof EventExecutor && ((EventExecutor) executor).inEventLoop();
1925 }
1926
1927 /**
1928 * Will either run the delegated task directly calling {@link Runnable#run()} and return {@code true} or will
1929 * offload the delegated task using {@link Executor#execute(Runnable)} and return {@code false}.
1930 *
1931 * If the task is offloaded it will take care to resume its work on the {@link EventExecutor} once there are no
1932 * more tasks to process.
1933 */
1934 private boolean runDelegatedTasks(boolean inUnwrap) {
1935 if (delegatedTaskExecutor == ImmediateExecutor.INSTANCE || inEventLoop(delegatedTaskExecutor)) {
1936 // We should run the task directly in the EventExecutor thread and not offload at all. As we are on the
1937 // EventLoop we can just run all tasks at once.
1938 for (;;) {
1939 Runnable task = engine.getDelegatedTask();
1940 if (task == null) {
1941 return true;
1942 }
1943 setState(STATE_PROCESS_TASK);
1944 if (task instanceof AsyncRunnable) {
1945 // Let's set the task to processing task before we try to execute it.
1946 boolean pending = false;
1947 try {
1948 AsyncRunnable asyncTask = (AsyncRunnable) task;
1949 AsyncTaskCompletionHandler completionHandler = new AsyncTaskCompletionHandler(inUnwrap);
1950 asyncTask.run(completionHandler);
1951 pending = completionHandler.resumeLater();
1952 if (pending) {
1953 return false;
1954 }
1955 } finally {
1956 if (!pending) {
1957 // The task has completed, lets clear the state. If it is not completed we will clear the
1958 // state once it is.
1959 clearState(STATE_PROCESS_TASK);
1960 directDelegatedTaskCompleted();
1961 }
1962 }
1963 } else {
1964 try {
1965 task.run();
1966 } finally {
1967 clearState(STATE_PROCESS_TASK);
1968 directDelegatedTaskCompleted();
1969 }
1970 }
1971 }
1972 } else {
1973 executeDelegatedTask(inUnwrap);
1974 return false;
1975 }
1976 }
1977
1978 private SslTasksRunner getTaskRunner(boolean inUnwrap) {
1979 return inUnwrap ? sslTaskRunnerForUnwrap : sslTaskRunner;
1980 }
1981
1982 private void executeDelegatedTask(boolean inUnwrap) {
1983 executeDelegatedTask(getTaskRunner(inUnwrap));
1984 }
1985
1986 private void executeDelegatedTask(SslTasksRunner task) {
1987 setState(STATE_PROCESS_TASK);
1988 try {
1989 delegatedTaskExecutor.execute(task);
1990 } catch (RejectedExecutionException e) {
1991 clearState(STATE_PROCESS_TASK);
1992 throw e;
1993 }
1994 }
1995
1996 private final class AsyncTaskCompletionHandler implements Runnable {
1997 private final boolean inUnwrap;
1998 boolean didRun;
1999 boolean resumeLater;
2000
2001 AsyncTaskCompletionHandler(boolean inUnwrap) {
2002 this.inUnwrap = inUnwrap;
2003 }
2004
2005 @Override
2006 public void run() {
2007 didRun = true;
2008 if (resumeLater) {
2009 getTaskRunner(inUnwrap).runComplete();
2010 }
2011 }
2012
2013 boolean resumeLater() {
2014 if (!didRun) {
2015 resumeLater = true;
2016 return true;
2017 }
2018 return false;
2019 }
2020 }
2021
2022 /**
2023 * {@link Runnable} that will be scheduled on the {@code delegatedTaskExecutor} and will take care
2024 * of resume work on the {@link EventExecutor} once the task was executed.
2025 */
2026 private final class SslTasksRunner implements Runnable {
2027 private final boolean inUnwrap;
2028 private final Runnable runCompleteTask = this::runComplete;
2029
2030 SslTasksRunner(boolean inUnwrap) {
2031 this.inUnwrap = inUnwrap;
2032 }
2033
2034 // Handle errors which happened during task processing.
2035 private void taskError(Throwable e) {
2036 if (inUnwrap) {
2037 // As the error happened while the task was scheduled as part of unwrap(...) we also need to ensure
2038 // we fire it through the pipeline as inbound error to be consistent with what we do in decode(...).
2039 //
2040 // This will also ensure we fail the handshake future and flush all produced data.
2041 try {
2042 handleUnwrapThrowable(ctx, e);
2043 } catch (Throwable cause) {
2044 safeExceptionCaught(cause);
2045 }
2046 } else {
2047 setHandshakeFailure(ctx, e);
2048 forceFlush(ctx);
2049 }
2050 }
2051
2052 // Try to call exceptionCaught(...)
2053 private void safeExceptionCaught(Throwable cause) {
2054 try {
2055 exceptionCaught(ctx, wrapIfNeeded(cause));
2056 } catch (Throwable error) {
2057 ctx.fireExceptionCaught(error);
2058 }
2059 }
2060
2061 private Throwable wrapIfNeeded(Throwable cause) {
2062 if (!inUnwrap) {
2063 // If we are not in unwrap(...) we can just rethrow without wrapping at all.
2064 return cause;
2065 }
2066 // As the exception would have been triggered by an inbound operation we will need to wrap it in a
2067 // DecoderException to mimic what a decoder would do when decode(...) throws.
2068 return cause instanceof DecoderException ? cause : new DecoderException(cause);
2069 }
2070
2071 private void tryDecodeAgain() {
2072 try {
2073 channelRead(ctx, Unpooled.EMPTY_BUFFER);
2074 } catch (Throwable cause) {
2075 safeExceptionCaught(cause);
2076 } finally {
2077 // As we called channelRead(...) we also need to call channelReadComplete(...) which
2078 // will ensure we either call ctx.fireChannelReadComplete() or will trigger a ctx.read() if
2079 // more data is needed.
2080 channelReadComplete0(ctx);
2081 }
2082 }
2083
2084 /**
2085 * Executed after the wrapped {@code task} was executed via {@code delegatedTaskExecutor} to resume work
2086 * on the {@link EventExecutor}.
2087 */
2088 private void resumeOnEventExecutor() {
2089 assert ctx.executor().inEventLoop();
2090 clearState(STATE_PROCESS_TASK);
2091 try {
2092 HandshakeStatus status = engine.getHandshakeStatus();
2093 switch (status) {
2094 // There is another task that needs to be executed and offloaded to the delegatingTaskExecutor as
2095 // a result of this. Let's reschedule....
2096 case NEED_TASK:
2097 executeDelegatedTask(this);
2098
2099 break;
2100
2101 // The handshake finished, lets notify about the completion of it and resume processing.
2102 case FINISHED:
2103 // Not handshaking anymore, lets notify about the completion if not done yet and resume processing.
2104 case NOT_HANDSHAKING:
2105 setHandshakeSuccess(); // NOT_HANDSHAKING -> workaround for android skipping FINISHED state.
2106 try {
2107 // Lets call wrap to ensure we produce the alert if there is any pending and also to
2108 // ensure we flush any queued data..
2109 wrap(ctx, inUnwrap);
2110 } catch (Throwable e) {
2111 taskError(e);
2112 return;
2113 }
2114 if (inUnwrap) {
2115 // If we were in the unwrap call when the task was processed we should also try to unwrap
2116 // non app data first as there may not anything left in the inbound buffer to process.
2117 unwrapNonAppData(ctx);
2118 }
2119
2120 // Flush now as we may have written some data as part of the wrap call.
2121 forceFlush(ctx);
2122
2123 tryDecodeAgain();
2124 break;
2125
2126 // We need more data so lets try to unwrap first and then call decode again which will feed us
2127 // with buffered data (if there is any).
2128 case NEED_UNWRAP:
2129 try {
2130 unwrapNonAppData(ctx);
2131 } catch (SSLException e) {
2132 handleUnwrapThrowable(ctx, e);
2133 return;
2134 }
2135 tryDecodeAgain();
2136 break;
2137
2138 // To make progress we need to call SSLEngine.wrap(...) which may produce more output data
2139 // that will be written to the Channel.
2140 case NEED_WRAP:
2141 try {
2142 if (!wrapNonAppData(ctx, false) && inUnwrap) {
2143 // The handshake finished in wrapNonAppData(...), we need to try call
2144 // unwrapNonAppData(...) as we may have some alert that we should read.
2145 //
2146 // This mimics what we would do when we are calling this method while in unwrap(...).
2147 unwrapNonAppData(ctx);
2148 }
2149
2150 // Flush now as we may have written some data as part of the wrap call.
2151 forceFlush(ctx);
2152 } catch (Throwable e) {
2153 taskError(e);
2154 return;
2155 }
2156
2157 // Now try to feed in more data that we have buffered.
2158 tryDecodeAgain();
2159 break;
2160
2161 default:
2162 // Should never reach here as we handle all cases.
2163 throw new AssertionError();
2164 }
2165 } catch (Throwable cause) {
2166 safeExceptionCaught(cause);
2167 } finally {
2168 delegatedTaskCompleted();
2169 }
2170 }
2171
2172 void runComplete() {
2173 EventExecutor executor = ctx.executor();
2174 if (executor.isShuttingDown()) {
2175 // The executor is already shutting down, just return.
2176 return;
2177 }
2178 // Jump back on the EventExecutor. We do this even if we are already on the EventLoop to guard against
2179 // reentrancy issues. Failing to do so could lead to the situation of tryDecode(...) be called and so
2180 // channelRead(...) while still in the decode loop. In this case channelRead(...) might release the input
2181 // buffer if its empty which would then result in an IllegalReferenceCountException when we try to continue
2182 // decoding.
2183 //
2184 // See https://github.com/netty/netty-tcnative/issues/680
2185 executor.execute(this::resumeOnEventExecutor);
2186 }
2187
2188 /**
2189 * Called when {@link SSLEngine#getDelegatedTask()} returned {@code null}. We only ever run one task at a
2190 * time (guarded by {@code STATE_PROCESS_TASK}), so nobody else will resume for us. If we were not resumed
2191 * yet, resume now on the {@link EventExecutor}.
2192 */
2193 private void resumeIfNoTaskIsPending() {
2194 EventExecutor executor = ctx.executor();
2195 if (executor.isShuttingDown()) {
2196 // The executor is already shutting down, just return.
2197 return;
2198 }
2199 executor.execute(new Runnable() {
2200 @Override
2201 public void run() {
2202 if (!isStateSet(STATE_PROCESS_TASK)) {
2203 // Somebody else already resumed.
2204 return;
2205 }
2206 resumeOnEventExecutor();
2207 }
2208 });
2209 }
2210
2211 @Override
2212 public void run() {
2213 try {
2214 Runnable task = engine.getDelegatedTask();
2215 if (task == null) {
2216 // The task was processed in the meantime, which means nobody will call runComplete() for us.
2217 // Make sure we resume if nobody else will, as otherwise STATE_PROCESS_TASK would stay set
2218 // forever and the handshake would stall.
2219 resumeIfNoTaskIsPending();
2220 return;
2221 }
2222 if (task instanceof AsyncRunnable) {
2223 AsyncRunnable asyncTask = (AsyncRunnable) task;
2224 asyncTask.run(runCompleteTask);
2225 } else {
2226 task.run();
2227 runComplete();
2228 }
2229 } catch (final Throwable cause) {
2230 handleException(cause);
2231 }
2232 }
2233
2234 private void handleException(final Throwable cause) {
2235 EventExecutor executor = ctx.executor();
2236 if (executor.inEventLoop()) {
2237 clearState(STATE_PROCESS_TASK);
2238 safeExceptionCaught(cause);
2239 delegatedTaskCompleted();
2240 } else {
2241 try {
2242 executor.execute(() -> {
2243 clearState(STATE_PROCESS_TASK);
2244 safeExceptionCaught(cause);
2245 delegatedTaskCompleted();
2246 });
2247 } catch (RejectedExecutionException ignore) {
2248 clearState(STATE_PROCESS_TASK);
2249 // the context itself will handle the rejected exception when try to schedule the operation so
2250 // ignore the RejectedExecutionException
2251 ctx.fireExceptionCaught(cause);
2252 }
2253 }
2254 }
2255 }
2256
2257 /**
2258 * Notify all the handshake futures about the successfully handshake
2259 * @return {@code true} if {@link #handshakePromise} was set successfully and a {@link SslHandshakeCompletionEvent}
2260 * was fired. {@code false} otherwise.
2261 */
2262 private boolean setHandshakeSuccess() throws SSLException {
2263 // Our control flow may invoke this method multiple times for a single FINISHED event. For example
2264 // wrapNonAppData may drain pendingUnencryptedWrites in wrap which transitions to handshake from FINISHED to
2265 // NOT_HANDSHAKING which invokes setHandshakeSuccess, and then wrapNonAppData also directly invokes this method.
2266 final SSLSession session = engine.getSession();
2267 if (resumptionController != null && !handshakePromise.isDone()) {
2268 try {
2269 if (resumptionController.validateResumeIfNeeded(engine) && logger.isDebugEnabled()) {
2270 logger.debug("{} Resumed and reauthenticated session", ctx.channel());
2271 }
2272 } catch (CertificateException e) {
2273 SSLHandshakeException exception = new SSLHandshakeException(e.getMessage());
2274 exception.initCause(e);
2275 throw exception;
2276 }
2277 }
2278 final boolean notified = !handshakePromise.isDone() && handshakePromise.trySuccess(ctx.channel());
2279 if (notified) {
2280 if (logger.isDebugEnabled()) {
2281 logger.debug(
2282 "{} HANDSHAKEN: protocol:{} cipher suite:{}",
2283 ctx.channel(),
2284 session.getProtocol(),
2285 session.getCipherSuite());
2286 }
2287 ctx.fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS);
2288 }
2289 if (isStateSet(STATE_READ_DURING_HANDSHAKE)) {
2290 clearState(STATE_READ_DURING_HANDSHAKE);
2291 if (!ctx.channel().config().isAutoRead()) {
2292 ctx.read();
2293 }
2294 }
2295 return notified;
2296 }
2297
2298 /**
2299 * Notify all the handshake futures about the failure during the handshake.
2300 */
2301 private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause) {
2302 setHandshakeFailure(ctx, cause, true, true, false);
2303 }
2304
2305 /**
2306 * Notify all the handshake futures about the failure during the handshake.
2307 */
2308 private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boolean closeInbound,
2309 boolean notify, boolean alwaysFlushAndClose) {
2310 try {
2311 // Release all resources such as internal buffers that SSLEngine is managing.
2312 setState(STATE_OUTBOUND_CLOSED);
2313 engine.closeOutbound();
2314
2315 if (closeInbound) {
2316 try {
2317 engine.closeInbound();
2318 } catch (SSLException e) {
2319 if (logger.isDebugEnabled()) {
2320 // only log in debug mode as it most likely harmless and latest chrome still trigger
2321 // this all the time.
2322 //
2323 // See https://github.com/netty/netty/issues/1340
2324 String msg = e.getMessage();
2325 if (msg == null || !(msg.contains("possible truncation attack") ||
2326 msg.contains("closing inbound before receiving peer's close_notify"))) {
2327 logger.debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e);
2328 }
2329 }
2330 }
2331 }
2332 if (handshakePromise.tryFailure(cause) || alwaysFlushAndClose) {
2333 SslUtils.handleHandshakeFailure(ctx, cause, notify);
2334 }
2335 } finally {
2336 // Ensure we remove and fail all pending writes in all cases and so release memory quickly.
2337 releaseAndFailAll(ctx, cause);
2338 }
2339 }
2340
2341 private void setHandshakeFailureTransportFailure(ChannelHandlerContext ctx, Throwable cause) {
2342 // If TLS control frames fail to write we are in an unknown state and may become out of
2343 // sync with our peer. We give up and close the channel. This will also take care of
2344 // cleaning up any outstanding state (e.g. handshake promise, queued unencrypted data).
2345 try {
2346 SSLException transportFailure = new SSLException("failure when writing TLS control frames", cause);
2347 releaseAndFailAll(ctx, transportFailure);
2348 if (handshakePromise.tryFailure(transportFailure)) {
2349 ctx.fireUserEventTriggered(new SslHandshakeCompletionEvent(transportFailure));
2350 }
2351 } finally {
2352 ctx.close();
2353 }
2354 }
2355
2356 private void releaseAndFailAll(ChannelHandlerContext ctx, Throwable cause) {
2357 if (resumptionController != null &&
2358 (!engine.getSession().isValid() || cause instanceof SSLHandshakeException)) {
2359 resumptionController.remove(engine());
2360 }
2361 if (pendingUnencryptedWrites != null) {
2362 pendingUnencryptedWrites.releaseAndFailAll(ctx, cause);
2363 }
2364 final ChannelPromise closeNotifyPromise = deferredCloseNotifyPromise;
2365 if (closeNotifyPromise != null) {
2366 deferredCloseNotifyPromise = null;
2367 closeNotifyPromise.tryFailure(cause);
2368 }
2369 }
2370
2371 private void notifyClosePromise(Throwable cause) {
2372 if (cause == null) {
2373 if (sslClosePromise.trySuccess(ctx.channel())) {
2374 ctx.fireUserEventTriggered(SslCloseCompletionEvent.SUCCESS);
2375 }
2376 } else {
2377 if (sslClosePromise.tryFailure(cause)) {
2378 ctx.fireUserEventTriggered(new SslCloseCompletionEvent(cause));
2379 }
2380 }
2381 }
2382
2383 private void closeOutboundAndChannel(
2384 final ChannelHandlerContext ctx, final ChannelPromise promise, boolean disconnect) throws Exception {
2385 setState(STATE_OUTBOUND_CLOSED);
2386
2387 if (!ctx.channel().isActive()) {
2388 engine.closeOutbound();
2389 if (disconnect) {
2390 ctx.disconnect(promise);
2391 } else {
2392 ctx.close(promise);
2393 }
2394 return;
2395 }
2396
2397 ChannelPromise closeNotifyPromise = ctx.newPromise();
2398 try {
2399 closeOutboundAndFlush(ctx, closeNotifyPromise, false);
2400 } finally {
2401 if (!isStateSet(STATE_CLOSE_NOTIFY)) {
2402 setState(STATE_CLOSE_NOTIFY);
2403 // It's important that we do not pass the original ChannelPromise to safeClose(...) as when flush(....)
2404 // throws an Exception it will be propagated to the AbstractChannelHandlerContext which will try
2405 // to fail the promise because of this. This will then fail as it was already completed by
2406 // safeClose(...). We create a new ChannelPromise and try to notify the original ChannelPromise
2407 // once it is complete. If we fail to do so we just ignore it as in this case it was failed already
2408 // because of a propagated Exception.
2409 //
2410 // See https://github.com/netty/netty/issues/5931
2411 safeClose(ctx, closeNotifyPromise, PromiseNotifier.cascade(false, ctx.newPromise(), promise));
2412 } else {
2413 /// We already handling the close_notify so just attach the promise to the sslClosePromise.
2414 sslClosePromise.addListener(f -> promise.setSuccess());
2415 }
2416 }
2417 }
2418
2419 private void flush(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
2420 if (pendingUnencryptedWrites != null) {
2421 pendingUnencryptedWrites.add(Unpooled.EMPTY_BUFFER, promise);
2422 } else {
2423 promise.setFailure(newPendingWritesNullException());
2424 }
2425 flush(ctx);
2426 }
2427
2428 @Override
2429 public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
2430 this.ctx = ctx;
2431 Channel channel = ctx.channel();
2432 pendingUnencryptedWrites = new SslHandlerCoalescingBufferQueue(channel, 16, engineType.wantsDirectBuffer) {
2433 @Override
2434 protected int wrapDataSize() {
2435 return SslHandler.this.wrapDataSize;
2436 }
2437 };
2438
2439 setOpensslEngineSocketFd(channel);
2440 boolean fastOpen = Boolean.TRUE.equals(channel.config().getOption(ChannelOption.TCP_FASTOPEN_CONNECT));
2441 boolean active = channel.isActive();
2442 if (active || fastOpen) {
2443 // Explicitly flush the handshake only if the channel is already active.
2444 // With TCP Fast Open, we write to the outbound buffer before the TCP connect is established.
2445 // The buffer will then be flushed as part of establishing the connection, saving us a round-trip.
2446 startHandshakeProcessing(active);
2447 // If we weren't able to include client_hello in the TCP SYN (e.g. no token, disabled at the OS) we have to
2448 // flush pending data in the outbound buffer later in channelActive().
2449 final ChannelOutboundBuffer outboundBuffer;
2450 if (fastOpen && ((outboundBuffer = channel.unsafe().outboundBuffer()) == null ||
2451 outboundBuffer.totalPendingWriteBytes() > 0)) {
2452 setState(STATE_NEEDS_FLUSH);
2453 }
2454 }
2455 }
2456
2457 private void startHandshakeProcessing(boolean flushAtEnd) {
2458 if (!isStateSet(STATE_HANDSHAKE_STARTED)) {
2459 setState(STATE_HANDSHAKE_STARTED);
2460 if (engine.getUseClientMode()) {
2461 // Begin the initial handshake.
2462 // channelActive() event has been fired already, which means this.channelActive() will
2463 // not be invoked. We have to initialize here instead.
2464 handshake(flushAtEnd);
2465 }
2466 applyHandshakeTimeout();
2467 } else if (isStateSet(STATE_NEEDS_FLUSH)) {
2468 forceFlush(ctx);
2469 }
2470 }
2471
2472 /**
2473 * Performs TLS renegotiation.
2474 */
2475 public Future<Channel> renegotiate() {
2476 ChannelHandlerContext ctx = this.ctx;
2477 if (ctx == null) {
2478 throw new IllegalStateException();
2479 }
2480
2481 return renegotiate(ctx.executor().newPromise());
2482 }
2483
2484 /**
2485 * Performs TLS renegotiation.
2486 */
2487 public Future<Channel> renegotiate(final Promise<Channel> promise) {
2488 ObjectUtil.checkNotNull(promise, "promise");
2489
2490 ChannelHandlerContext ctx = this.ctx;
2491 if (ctx == null) {
2492 throw new IllegalStateException();
2493 }
2494
2495 EventExecutor executor = ctx.executor();
2496 if (!executor.inEventLoop()) {
2497 executor.execute(() -> renegotiateOnEventLoop(promise));
2498 return promise;
2499 }
2500
2501 renegotiateOnEventLoop(promise);
2502 return promise;
2503 }
2504
2505 private void renegotiateOnEventLoop(final Promise<Channel> newHandshakePromise) {
2506 final Promise<Channel> oldHandshakePromise = handshakePromise;
2507 if (!oldHandshakePromise.isDone()) {
2508 // There's no need to handshake because handshake is in progress already.
2509 // Merge the new promise into the old one.
2510 PromiseNotifier.cascade(oldHandshakePromise, newHandshakePromise);
2511 } else {
2512 handshakePromise = newHandshakePromise;
2513 handshake(true);
2514 applyHandshakeTimeout();
2515 }
2516 }
2517
2518 /**
2519 * Performs TLS (re)negotiation.
2520 * @param flushAtEnd Set to {@code true} if the outbound buffer should be flushed (written to the network) at the
2521 * end. Set to {@code false} if the handshake will be flushed later, e.g. as part of TCP Fast Open
2522 * connect.
2523 */
2524 private void handshake(boolean flushAtEnd) {
2525 if (engine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
2526 // Not all SSLEngine implementations support calling beginHandshake multiple times while a handshake
2527 // is in progress. See https://github.com/netty/netty/issues/4718.
2528 return;
2529 }
2530 if (handshakePromise.isDone()) {
2531 // If the handshake is done already lets just return directly as there is no need to trigger it again.
2532 // This can happen if the handshake(...) was triggered before we called channelActive(...) by a
2533 // flush() that was triggered by a ChannelFutureListener that was added to the ChannelFuture returned
2534 // from the connect(...) method. In this case we will see the flush() happen before we had a chance to
2535 // call fireChannelActive() on the pipeline.
2536 return;
2537 }
2538
2539 // Begin handshake.
2540 final ChannelHandlerContext ctx = this.ctx;
2541 try {
2542 engine.beginHandshake();
2543 wrapNonAppData(ctx, false);
2544 } catch (Throwable e) {
2545 setHandshakeFailure(ctx, e);
2546 } finally {
2547 if (flushAtEnd) {
2548 forceFlush(ctx);
2549 }
2550 }
2551 }
2552
2553 private void applyHandshakeTimeout() {
2554 final Promise<Channel> localHandshakePromise = this.handshakePromise;
2555
2556 // Set timeout if necessary.
2557 final long handshakeTimeoutMillis = this.handshakeTimeoutMillis;
2558 if (handshakeTimeoutMillis <= 0 || localHandshakePromise.isDone()) {
2559 return;
2560 }
2561
2562 final Future<?> timeoutFuture = ctx.executor().schedule(() -> {
2563 if (localHandshakePromise.isDone()) {
2564 return;
2565 }
2566 SSLException exception =
2567 new SslHandshakeTimeoutException("handshake timed out after " + handshakeTimeoutMillis + "ms");
2568 try {
2569 if (localHandshakePromise.tryFailure(exception)) {
2570 SslUtils.handleHandshakeFailure(ctx, exception, true);
2571 }
2572 } finally {
2573 releaseAndFailAll(ctx, exception);
2574 }
2575 }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
2576
2577 // Cancel the handshake timeout when handshake is finished.
2578 localHandshakePromise.addListener(f -> timeoutFuture.cancel(false));
2579 }
2580
2581 private void forceFlush(ChannelHandlerContext ctx) {
2582 clearState(STATE_NEEDS_FLUSH);
2583 ctx.flush();
2584 }
2585
2586 private void setOpensslEngineSocketFd(Channel c) {
2587 if (c instanceof UnixChannel && engine instanceof ReferenceCountedOpenSslEngine) {
2588 ((ReferenceCountedOpenSslEngine) engine).bioSetFd(((UnixChannel) c).fd().intValue());
2589 }
2590 }
2591
2592 /**
2593 * Issues an initial TLS handshake once connected when used in client-mode
2594 */
2595 @Override
2596 public void channelActive(final ChannelHandlerContext ctx) throws Exception {
2597 setOpensslEngineSocketFd(ctx.channel());
2598 if (!startTls) {
2599 startHandshakeProcessing(true);
2600 }
2601 ctx.fireChannelActive();
2602 }
2603
2604 private void safeClose(
2605 final ChannelHandlerContext ctx, final ChannelFuture flushFuture,
2606 final ChannelPromise promise) {
2607 if (!ctx.channel().isActive()) {
2608 ctx.close(promise);
2609 return;
2610 }
2611
2612 final Future<?> timeoutFuture;
2613 if (!flushFuture.isDone()) {
2614 long closeNotifyTimeout = closeNotifyFlushTimeoutMillis;
2615 if (closeNotifyTimeout > 0) {
2616 // Force-close the connection if close_notify is not fully sent in time.
2617 timeoutFuture = ctx.executor().schedule(() -> {
2618 // May be done in the meantime as cancel(...) is only best effort.
2619 if (!flushFuture.isDone()) {
2620 logger.warn("{} Last write attempt timed out; force-closing the connection.",
2621 ctx.channel());
2622 addCloseListener(ctx.close(ctx.newPromise()), promise);
2623 }
2624 }, closeNotifyTimeout, TimeUnit.MILLISECONDS);
2625 } else {
2626 timeoutFuture = null;
2627 }
2628 } else {
2629 timeoutFuture = null;
2630 }
2631
2632 // Close the connection if close_notify is sent in time.
2633 flushFuture.addListener(f -> {
2634 if (timeoutFuture != null) {
2635 timeoutFuture.cancel(false);
2636 }
2637 final long closeNotifyReadTimeout = closeNotifyReadTimeoutMillis;
2638 if (closeNotifyReadTimeout <= 0) {
2639 // Trigger the close in all cases to make sure the promise is notified
2640 // See https://github.com/netty/netty/issues/2358
2641 addCloseListener(ctx.close(ctx.newPromise()), promise);
2642 } else {
2643 final Future<?> closeNotifyReadTimeoutFuture;
2644
2645 if (!sslClosePromise.isDone()) {
2646 closeNotifyReadTimeoutFuture = ctx.executor().schedule(() -> {
2647 if (!sslClosePromise.isDone()) {
2648 logger.debug(
2649 "{} did not receive close_notify in {}ms; force-closing the connection.",
2650 ctx.channel(), closeNotifyReadTimeout);
2651
2652 // Do the close now...
2653 addCloseListener(ctx.close(ctx.newPromise()), promise);
2654 }
2655 }, closeNotifyReadTimeout, TimeUnit.MILLISECONDS);
2656 } else {
2657 closeNotifyReadTimeoutFuture = null;
2658 }
2659
2660 // Do the close once the we received the close_notify.
2661 sslClosePromise.addListener(future -> {
2662 if (closeNotifyReadTimeoutFuture != null) {
2663 closeNotifyReadTimeoutFuture.cancel(false);
2664 }
2665 addCloseListener(ctx.close(ctx.newPromise()), promise);
2666 });
2667 }
2668 });
2669 }
2670
2671 private static void addCloseListener(ChannelFuture future, ChannelPromise promise) {
2672 // We notify the promise in the ChannelPromiseNotifier as there is a "race" where the close(...) call
2673 // by the timeoutFuture and the close call in the flushFuture listener will be called. Because of
2674 // this we need to use trySuccess() and tryFailure(...) as otherwise we can cause an
2675 // IllegalStateException.
2676 // Also we not want to log if the notification happens as this is expected in some cases.
2677 // See https://github.com/netty/netty/issues/5598
2678 PromiseNotifier.cascade(false, future, promise);
2679 }
2680
2681 /**
2682 * Always prefer a direct buffer when it's pooled, so that we reduce the number of memory copies
2683 * in {@link OpenSslEngine}.
2684 */
2685 private ByteBuf allocate(ChannelHandlerContext ctx, int capacity) {
2686 ByteBufAllocator alloc = ctx.alloc();
2687 if (engineType.wantsDirectBuffer) {
2688 return alloc.directBuffer(capacity);
2689 } else {
2690 return alloc.buffer(capacity);
2691 }
2692 }
2693
2694 /**
2695 * Allocates an outbound network buffer for {@link SSLEngine#wrap(ByteBuffer, ByteBuffer)} which can encrypt
2696 * the specified amount of pending bytes.
2697 */
2698 private ByteBuf allocateOutNetBuf(ChannelHandlerContext ctx, int pendingBytes, int numComponents) {
2699 return engineType.allocateWrapBuffer(this, ctx.alloc(), pendingBytes, numComponents);
2700 }
2701
2702 private boolean isStateSet(int bit) {
2703 return (state & bit) == bit;
2704 }
2705
2706 private void setState(int bit) {
2707 state |= bit;
2708 }
2709
2710 private void clearState(int bit) {
2711 state &= ~bit;
2712 }
2713
2714 /**
2715 * The promise of a write of encrypted application data, which knows how many bytes it contains.
2716 */
2717 private static final class EncryptedWritePromise extends DefaultChannelPromise {
2718 int bytes;
2719
2720 EncryptedWritePromise(ChannelHandlerContext ctx) {
2721 super(ctx.channel(), ctx.executor());
2722 }
2723 }
2724
2725 private final class LazyChannelPromise extends DefaultPromise<Channel> {
2726
2727 @Override
2728 protected EventExecutor executor() {
2729 if (ctx == null) {
2730 throw new IllegalStateException();
2731 }
2732 return ctx.executor();
2733 }
2734
2735 @Override
2736 protected void checkDeadLock() {
2737 if (ctx == null) {
2738 // If ctx is null the handlerAdded(...) callback was not called, in this case the checkDeadLock()
2739 // method was called from another Thread then the one that is used by ctx.executor(). We need to
2740 // guard against this as a user can see a race if handshakeFuture().sync() is called but the
2741 // handlerAdded(..) method was not yet as it is called from the EventExecutor of the
2742 // ChannelHandlerContext. If we not guard against this super.checkDeadLock() would cause an
2743 // IllegalStateException when trying to call executor().
2744 return;
2745 }
2746 super.checkDeadLock();
2747 }
2748 }
2749 }