Class SslHandler
- java.lang.Object
-
- io.netty.channel.ChannelHandlerAdapter
-
- io.netty.channel.ChannelInboundHandlerAdapter
-
- io.netty.handler.codec.ByteToMessageDecoder
-
- io.netty.handler.ssl.SslHandler
-
- All Implemented Interfaces:
ChannelHandler,ChannelInboundHandler,ChannelOutboundHandler
public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundHandler
Adds SSL · TLS and StartTLS support to aChannel. Please refer to the "SecureChat" example in the distribution or the web site for the detailed usage.Beginning the handshake
Beside using the handshake
ChannelFutureto get notified about the completion of the handshake it's also possible to detect it by implement theChannelInboundHandler.userEventTriggered(ChannelHandlerContext, Object)method and check for aSslHandshakeCompletionEvent.Handshake
The handshake will be automatically issued for you once the
Channelis active andSSLEngine.getUseClientMode()returnstrue. So no need to bother with it by your self.Closing the session
To close the SSL session, the
closeOutbound()method should be called to send theclose_notifymessage to the remote peer. One exception is when you close theChannel-SslHandlerintercepts the close request and send theclose_notifymessage before the channel closure automatically. Once the SSL session is closed, it is not reusable, and consequently you should create a newSslHandlerwith a newSSLEngineas explained in the following section.Restarting the session
To restart the SSL session, you must remove the existing closed
SslHandlerfrom theChannelPipeline, insert a newSslHandlerwith a newSSLEngineinto the pipeline, and start the handshake process as described in the first section.Implementing StartTLS
StartTLS is the communication pattern that secures the wire in the middle of the plaintext connection. Please note that it is different from SSL · TLS, that secures the wire from the beginning of the connection. Typically, StartTLS is composed of three steps:
- Client sends a StartTLS request to server.
- Server sends a StartTLS response to client.
- Client begins SSL handshake.
- create a new
SslHandlerinstance withstartTlsflag set totrue, - insert the
SslHandlerto theChannelPipeline, and - write a StartTLS response.
SslHandlerbefore sending the StartTLS response. Otherwise the client can send begin SSL handshake beforeSslHandleris inserted to theChannelPipeline, causing data corruption.The client-side implementation is much simpler.
- Write a StartTLS request,
- wait for the StartTLS response,
- create a new
SslHandlerinstance withstartTlsflag set tofalse, - insert the
SslHandlerto theChannelPipeline, and - Initiate SSL handshake.
Known issues
Because of a known issue with the current implementation of the SslEngine that comes with Java it may be possible that you see blocked IO-Threads while a full GC is done.
So if you are affected you can workaround this problem by adjust the cache settings like shown below:
SslContext context = ...; context.getServerSessionContext().setSessionCacheSize(someSaneSize); context.getServerSessionContext().setSessionTime(someSameTimeout);What values to use here depends on the nature of your application and should be set based on monitoring and debugging of it. For more details see #832 in our issue tracker.
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class io.netty.handler.codec.ByteToMessageDecoder
ByteToMessageDecoder.Cumulator
-
Nested classes/interfaces inherited from interface io.netty.channel.ChannelHandler
ChannelHandler.Sharable
-
-
Field Summary
-
Fields inherited from class io.netty.handler.codec.ByteToMessageDecoder
COMPOSITE_CUMULATOR, MERGE_CUMULATOR
-
-
Constructor Summary
Constructors Constructor Description SslHandler(javax.net.ssl.SSLEngine engine)Creates a new instance which runs all delegated tasks directly on theEventExecutor.SslHandler(javax.net.ssl.SSLEngine engine, boolean startTls)Creates a new instance which runs all delegated tasks directly on theEventExecutor.SslHandler(javax.net.ssl.SSLEngine engine, boolean startTls, java.util.concurrent.Executor delegatedTaskExecutor)Creates a new instance.SslHandler(javax.net.ssl.SSLEngine engine, java.util.concurrent.Executor delegatedTaskExecutor)Creates a new instance.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description java.lang.StringapplicationProtocol()Returns the name of the current application-level protocol.voidbind(ChannelHandlerContext ctx, java.net.SocketAddress localAddress, ChannelPromise promise)Called once a bind operation is made.voidchannelActive(ChannelHandlerContext ctx)Issues an initial TLS handshake once connected when used in client-modevoidchannelInactive(ChannelHandlerContext ctx)CallsChannelHandlerContext.fireChannelInactive()to forward to the nextChannelInboundHandlerin theChannelPipeline.voidchannelReadComplete(ChannelHandlerContext ctx)CallsChannelHandlerContext.fireChannelReadComplete()to forward to the nextChannelInboundHandlerin theChannelPipeline.ChannelFutureclose()Deprecated.voidclose(ChannelHandlerContext ctx, ChannelPromise promise)Called once a close operation is made.ChannelFutureclose(ChannelPromise promise)Deprecated.ChannelFuturecloseOutbound()Sends an SSLclose_notifymessage to the specified channel and destroys the underlyingSSLEngine.ChannelFuturecloseOutbound(ChannelPromise promise)Sends an SSLclose_notifymessage to the specified channel and destroys the underlyingSSLEngine.voidconnect(ChannelHandlerContext ctx, java.net.SocketAddress remoteAddress, java.net.SocketAddress localAddress, ChannelPromise promise)Called once a connect operation is made.protected voiddecode(ChannelHandlerContext ctx, ByteBuf in, java.util.List<java.lang.Object> out)Decode the from oneByteBufto an other.voidderegister(ChannelHandlerContext ctx, ChannelPromise promise)Called once a deregister operation is made from the current registeredEventLoop.voiddisconnect(ChannelHandlerContext ctx, ChannelPromise promise)Called once a disconnect operation is made.javax.net.ssl.SSLEngineengine()Returns theSSLEnginewhich is used by this handler.voidexceptionCaught(ChannelHandlerContext ctx, java.lang.Throwable cause)CallsChannelHandlerContext.fireExceptionCaught(Throwable)to forward to the nextChannelHandlerin theChannelPipeline.voidflush(ChannelHandlerContext ctx)Called once a flush operation is made.longgetCloseNotifyFlushTimeoutMillis()Gets the timeout for flushing the close_notify that was triggered by closing theChannel.longgetCloseNotifyReadTimeoutMillis()Gets the timeout (in ms) for receiving the response for the close_notify that was triggered by closing theChannel.longgetCloseNotifyTimeoutMillis()Deprecated.longgetHandshakeTimeoutMillis()voidhandlerAdded(ChannelHandlerContext ctx)Do nothing by default, sub-classes may override this method.voidhandlerRemoved0(ChannelHandlerContext ctx)Gets called after theByteToMessageDecoderwas removed from the actual context and it doesn't handle events anymore.Future<Channel>handshakeFuture()Returns aFuturethat will get notified once the current TLS handshake completes.static booleanisEncrypted(ByteBuf buffer)Deprecated.static booleanisEncrypted(ByteBuf buffer, boolean probeSSLv2)Returnstrueif the givenByteBufis encrypted.voidread(ChannelHandlerContext ctx)InterceptsChannelHandlerContext.read().Future<Channel>renegotiate()Performs TLS renegotiation.Future<Channel>renegotiate(Promise<Channel> promise)Performs TLS renegotiation.voidsetCloseNotifyFlushTimeout(long closeNotifyFlushTimeout, java.util.concurrent.TimeUnit unit)Sets the timeout for flushing the close_notify that was triggered by closing theChannel.voidsetCloseNotifyFlushTimeoutMillis(long closeNotifyFlushTimeoutMillis)voidsetCloseNotifyReadTimeout(long closeNotifyReadTimeout, java.util.concurrent.TimeUnit unit)Sets the timeout for receiving the response for the close_notify that was triggered by closing theChannel.voidsetCloseNotifyReadTimeoutMillis(long closeNotifyReadTimeoutMillis)voidsetCloseNotifyTimeout(long closeNotifyTimeout, java.util.concurrent.TimeUnit unit)Deprecated.voidsetCloseNotifyTimeoutMillis(long closeNotifyFlushTimeoutMillis)Deprecated.voidsetHandshakeTimeout(long handshakeTimeout, java.util.concurrent.TimeUnit unit)voidsetHandshakeTimeoutMillis(long handshakeTimeoutMillis)voidsetWrapDataSize(int wrapDataSize)Sets the number of bytes to pass to eachSSLEngine.wrap(ByteBuffer[], int, int, ByteBuffer)call.Future<Channel>sslCloseFuture()Return theFuturethat will get notified if the inbound of theSSLEngineis closed.voidwrite(ChannelHandlerContext ctx, java.lang.Object msg, ChannelPromise promise)Called once a write operation is made.-
Methods inherited from class io.netty.handler.codec.ByteToMessageDecoder
actualReadableBytes, callDecode, channelRead, decodeLast, discardSomeReadBytes, handlerRemoved, internalBuffer, isSingleDecode, setCumulator, setDiscardAfterReads, setSingleDecode, userEventTriggered
-
Methods inherited from class io.netty.channel.ChannelInboundHandlerAdapter
channelRegistered, channelUnregistered, channelWritabilityChanged
-
Methods inherited from class io.netty.channel.ChannelHandlerAdapter
ensureNotSharable, isSharable
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
Methods inherited from interface io.netty.channel.ChannelHandler
handlerRemoved
-
-
-
-
Constructor Detail
-
SslHandler
public SslHandler(javax.net.ssl.SSLEngine engine)
Creates a new instance which runs all delegated tasks directly on theEventExecutor.- Parameters:
engine- theSSLEnginethis handler will use
-
SslHandler
public SslHandler(javax.net.ssl.SSLEngine engine, boolean startTls)Creates a new instance which runs all delegated tasks directly on theEventExecutor.- Parameters:
engine- theSSLEnginethis handler will usestartTls-trueif the first write request shouldn't be encrypted by theSSLEngine
-
SslHandler
public SslHandler(javax.net.ssl.SSLEngine engine, java.util.concurrent.Executor delegatedTaskExecutor)Creates a new instance.- Parameters:
engine- theSSLEnginethis handler will usedelegatedTaskExecutor- theExecutorthat will be used to execute tasks that are returned bySSLEngine.getDelegatedTask().
-
SslHandler
public SslHandler(javax.net.ssl.SSLEngine engine, boolean startTls, java.util.concurrent.Executor delegatedTaskExecutor)Creates a new instance.- Parameters:
engine- theSSLEnginethis handler will usestartTls-trueif the first write request shouldn't be encrypted by theSSLEnginedelegatedTaskExecutor- theExecutorthat will be used to execute tasks that are returned bySSLEngine.getDelegatedTask().
-
-
Method Detail
-
getHandshakeTimeoutMillis
public long getHandshakeTimeoutMillis()
-
setHandshakeTimeout
public void setHandshakeTimeout(long handshakeTimeout, java.util.concurrent.TimeUnit unit)
-
setHandshakeTimeoutMillis
public void setHandshakeTimeoutMillis(long handshakeTimeoutMillis)
-
setWrapDataSize
@UnstableApi public final void setWrapDataSize(int wrapDataSize)
Sets the number of bytes to pass to eachSSLEngine.wrap(ByteBuffer[], int, int, ByteBuffer)call.This value will partition data which is passed to write
write(ChannelHandlerContext, Object, ChannelPromise). The partitioning will work as follows:- If
wrapDataSize <= 0then we will write each data chunk as is. - If
wrapDataSize > data sizethen we will attempt to aggregate multiple data chunks together. - If
wrapDataSize > data sizeElse ifwrapDataSize <= data sizethen we will divide the data into chunks ofwrapDataSizewhen writing.
If the
SSLEnginedoesn't support a gather wrap operation (e.g.SslProvider.OPENSSL) then aggregating data before wrapping can help reduce the ratio between TLS overhead vs data payload which will lead to better goodput. Writing fixed chunks of data can also help target the underlying transport's (e.g. TCP) frame size. Under lossy/congested network conditions this may help the peer get full TLS packets earlier and be able to do work sooner, as opposed to waiting for the all the pieces of the TLS packet to arrive.- Parameters:
wrapDataSize- the number of bytes which will be passed to eachSSLEngine.wrap(ByteBuffer[], int, int, ByteBuffer)call.
- If
-
getCloseNotifyTimeoutMillis
@Deprecated public long getCloseNotifyTimeoutMillis()
Deprecated.
-
setCloseNotifyTimeout
@Deprecated public void setCloseNotifyTimeout(long closeNotifyTimeout, java.util.concurrent.TimeUnit unit)Deprecated.
-
setCloseNotifyTimeoutMillis
@Deprecated public void setCloseNotifyTimeoutMillis(long closeNotifyFlushTimeoutMillis)
Deprecated.
-
getCloseNotifyFlushTimeoutMillis
public final long getCloseNotifyFlushTimeoutMillis()
-
setCloseNotifyFlushTimeout
public final void setCloseNotifyFlushTimeout(long closeNotifyFlushTimeout, java.util.concurrent.TimeUnit unit)
-
setCloseNotifyFlushTimeoutMillis
public final void setCloseNotifyFlushTimeoutMillis(long closeNotifyFlushTimeoutMillis)
-
getCloseNotifyReadTimeoutMillis
public final long getCloseNotifyReadTimeoutMillis()
-
setCloseNotifyReadTimeout
public final void setCloseNotifyReadTimeout(long closeNotifyReadTimeout, java.util.concurrent.TimeUnit unit)
-
setCloseNotifyReadTimeoutMillis
public final void setCloseNotifyReadTimeoutMillis(long closeNotifyReadTimeoutMillis)
-
engine
public javax.net.ssl.SSLEngine engine()
Returns theSSLEnginewhich is used by this handler.
-
applicationProtocol
public java.lang.String applicationProtocol()
Returns the name of the current application-level protocol.- Returns:
- the protocol name or
nullif application-level protocol has not been negotiated
-
handshakeFuture
public Future<Channel> handshakeFuture()
Returns aFuturethat will get notified once the current TLS handshake completes.- Returns:
- the
Futurefor the initial TLS handshake ifrenegotiate()was not invoked. TheFuturefor the most recent TLS renegotiation otherwise.
-
close
@Deprecated public ChannelFuture close()
Deprecated.UsecloseOutbound()
-
close
@Deprecated public ChannelFuture close(ChannelPromise promise)
Deprecated.
-
closeOutbound
public ChannelFuture closeOutbound()
Sends an SSLclose_notifymessage to the specified channel and destroys the underlyingSSLEngine. This will not close the underlyingChannel. If you want to also close theChanneluseChannel.close()orChannelOutboundInvoker.close()
-
closeOutbound
public ChannelFuture closeOutbound(ChannelPromise promise)
Sends an SSLclose_notifymessage to the specified channel and destroys the underlyingSSLEngine. This will not close the underlyingChannel. If you want to also close theChanneluseChannel.close()orChannelOutboundInvoker.close()
-
sslCloseFuture
public Future<Channel> sslCloseFuture()
Return theFuturethat will get notified if the inbound of theSSLEngineis closed. This method will return the sameFutureall the time.- See Also:
SSLEngine
-
handlerRemoved0
public void handlerRemoved0(ChannelHandlerContext ctx) throws java.lang.Exception
Description copied from class:ByteToMessageDecoderGets called after theByteToMessageDecoderwas removed from the actual context and it doesn't handle events anymore.- Overrides:
handlerRemoved0in classByteToMessageDecoder- Throws:
java.lang.Exception
-
bind
public void bind(ChannelHandlerContext ctx, java.net.SocketAddress localAddress, ChannelPromise promise) throws java.lang.Exception
Description copied from interface:ChannelOutboundHandlerCalled once a bind operation is made.- Specified by:
bindin interfaceChannelOutboundHandler- Parameters:
ctx- theChannelHandlerContextfor which the bind operation is madelocalAddress- theSocketAddressto which it should boundpromise- theChannelPromiseto notify once the operation completes- Throws:
java.lang.Exception- thrown if an error occurs
-
connect
public void connect(ChannelHandlerContext ctx, java.net.SocketAddress remoteAddress, java.net.SocketAddress localAddress, ChannelPromise promise) throws java.lang.Exception
Description copied from interface:ChannelOutboundHandlerCalled once a connect operation is made.- Specified by:
connectin interfaceChannelOutboundHandler- Parameters:
ctx- theChannelHandlerContextfor which the connect operation is maderemoteAddress- theSocketAddressto which it should connectlocalAddress- theSocketAddresswhich is used as source on connectpromise- theChannelPromiseto notify once the operation completes- Throws:
java.lang.Exception- thrown if an error occurs
-
deregister
public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws java.lang.Exception
Description copied from interface:ChannelOutboundHandlerCalled once a deregister operation is made from the current registeredEventLoop.- Specified by:
deregisterin interfaceChannelOutboundHandler- Parameters:
ctx- theChannelHandlerContextfor which the close operation is madepromise- theChannelPromiseto notify once the operation completes- Throws:
java.lang.Exception- thrown if an error occurs
-
disconnect
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws java.lang.Exception
Description copied from interface:ChannelOutboundHandlerCalled once a disconnect operation is made.- Specified by:
disconnectin interfaceChannelOutboundHandler- Parameters:
ctx- theChannelHandlerContextfor which the disconnect operation is madepromise- theChannelPromiseto notify once the operation completes- Throws:
java.lang.Exception- thrown if an error occurs
-
close
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws java.lang.Exception
Description copied from interface:ChannelOutboundHandlerCalled once a close operation is made.- Specified by:
closein interfaceChannelOutboundHandler- Parameters:
ctx- theChannelHandlerContextfor which the close operation is madepromise- theChannelPromiseto notify once the operation completes- Throws:
java.lang.Exception- thrown if an error occurs
-
read
public void read(ChannelHandlerContext ctx) throws java.lang.Exception
Description copied from interface:ChannelOutboundHandlerInterceptsChannelHandlerContext.read().- Specified by:
readin interfaceChannelOutboundHandler- Throws:
java.lang.Exception
-
write
public void write(ChannelHandlerContext ctx, java.lang.Object msg, ChannelPromise promise) throws java.lang.Exception
Description copied from interface:ChannelOutboundHandlerCalled once a write operation is made. The write operation will write the messages through theChannelPipeline. Those are then ready to be flushed to the actualChannelonceChannel.flush()is called- Specified by:
writein interfaceChannelOutboundHandler- Parameters:
ctx- theChannelHandlerContextfor which the write operation is mademsg- the message to writepromise- theChannelPromiseto notify once the operation completes- Throws:
java.lang.Exception- thrown if an error occurs
-
flush
public void flush(ChannelHandlerContext ctx) throws java.lang.Exception
Description copied from interface:ChannelOutboundHandlerCalled once a flush operation is made. The flush operation will try to flush out all previous written messages that are pending.- Specified by:
flushin interfaceChannelOutboundHandler- Parameters:
ctx- theChannelHandlerContextfor which the flush operation is made- Throws:
java.lang.Exception- thrown if an error occurs
-
channelInactive
public void channelInactive(ChannelHandlerContext ctx) throws java.lang.Exception
Description copied from class:ChannelInboundHandlerAdapterCallsChannelHandlerContext.fireChannelInactive()to forward to the nextChannelInboundHandlerin theChannelPipeline. Sub-classes may override this method to change behavior.- Specified by:
channelInactivein interfaceChannelInboundHandler- Overrides:
channelInactivein classByteToMessageDecoder- Throws:
java.lang.Exception
-
exceptionCaught
public void exceptionCaught(ChannelHandlerContext ctx, java.lang.Throwable cause) throws java.lang.Exception
Description copied from class:ChannelInboundHandlerAdapterCallsChannelHandlerContext.fireExceptionCaught(Throwable)to forward to the nextChannelHandlerin theChannelPipeline. Sub-classes may override this method to change behavior.- Specified by:
exceptionCaughtin interfaceChannelHandler- Specified by:
exceptionCaughtin interfaceChannelInboundHandler- Overrides:
exceptionCaughtin classChannelInboundHandlerAdapter- Throws:
java.lang.Exception
-
isEncrypted
@Deprecated public static boolean isEncrypted(ByteBuf buffer)
Deprecated.Returnstrueif the givenByteBufis encrypted. Be aware that this method will not increase the readerIndex of the givenByteBuf.- Parameters:
buffer- TheByteBufto read from. Be aware that it must have at least 5 bytes to read, otherwise it will throw anIllegalArgumentException.- Returns:
- encrypted
trueif theByteBufis encrypted,falseotherwise. - Throws:
java.lang.IllegalArgumentException- Is thrown if the givenByteBufhas not at least 5 bytes to read.
-
isEncrypted
public static boolean isEncrypted(ByteBuf buffer, boolean probeSSLv2)
Returnstrueif the givenByteBufis encrypted. Be aware that this method will not increase the readerIndex of the givenByteBuf.- Parameters:
buffer- TheByteBufto read from. Be aware that it must have at least 5 bytes to read, otherwise it will throw anIllegalArgumentException.probeSSLv2-trueif the inputbuffermight be SSLv2. Iftrueis used this methods might produce false-positives in some cases so it's strongly suggested to usefalse.- Returns:
- encrypted
trueif theByteBufis encrypted,falseotherwise. - Throws:
java.lang.IllegalArgumentException- Is thrown if the givenByteBufhas not at least 5 bytes to read.
-
decode
protected void decode(ChannelHandlerContext ctx, ByteBuf in, java.util.List<java.lang.Object> out) throws javax.net.ssl.SSLException
Description copied from class:ByteToMessageDecoderDecode the from oneByteBufto an other. This method will be called till either the inputByteBufhas nothing to read when return from this method or till nothing was read from the inputByteBuf.- Specified by:
decodein classByteToMessageDecoder- Parameters:
ctx- theChannelHandlerContextwhich thisByteToMessageDecoderbelongs toin- theByteBuffrom which to read dataout- theListto which decoded messages should be added- Throws:
javax.net.ssl.SSLException
-
channelReadComplete
public void channelReadComplete(ChannelHandlerContext ctx) throws java.lang.Exception
Description copied from class:ChannelInboundHandlerAdapterCallsChannelHandlerContext.fireChannelReadComplete()to forward to the nextChannelInboundHandlerin theChannelPipeline. Sub-classes may override this method to change behavior.- Specified by:
channelReadCompletein interfaceChannelInboundHandler- Overrides:
channelReadCompletein classByteToMessageDecoder- Throws:
java.lang.Exception
-
handlerAdded
public void handlerAdded(ChannelHandlerContext ctx) throws java.lang.Exception
Description copied from class:ChannelHandlerAdapterDo nothing by default, sub-classes may override this method.- Specified by:
handlerAddedin interfaceChannelHandler- Overrides:
handlerAddedin classChannelHandlerAdapter- Throws:
java.lang.Exception
-
renegotiate
public Future<Channel> renegotiate(Promise<Channel> promise)
Performs TLS renegotiation.
-
channelActive
public void channelActive(ChannelHandlerContext ctx) throws java.lang.Exception
Issues an initial TLS handshake once connected when used in client-mode- Specified by:
channelActivein interfaceChannelInboundHandler- Overrides:
channelActivein classChannelInboundHandlerAdapter- Throws:
java.lang.Exception
-
-