mirror of
https://github.com/apple/swift-nio-ssl
synced 2026-11-29 05:24:23 +00:00
Add a timeout for TLS shutdown. (#100)
Motivation: The remote peer may not always respond to a close notify. This would leave the SSL handler waiting to shutdown. The shutdown should timeout in these cases to ensure shutdown completes. Modifications: - Added a shutdown timeout to the NIOSSLHandler, and a configurable timeout amount to TLSConfiguration. - Added a test to validate timing out a shutdown. Result: TLS shutdown will complete even if the remote peer does not respond to a close notify.
This commit is contained in:
1 parent
ea842bd52b
commit
4f9d64ddd0
7 files changed
+90
-11
No files matched your search
@@ -50,6 +50,6 @@ public final class NIOSSLClientHandler: NIOSSLHandler {
|
||||
connection.setVerificationCallback(verificationCallback)
|
||||
}
|
||||
|
||||
super.init(connection: connection)
|
||||
super.init(connection: connection, shutdownTimeout: context.configuration.shutdownTimeout)
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo
|
||||
case handshaking
|
||||
case active
|
||||
case unwrapping
|
||||
case closing
|
||||
case closing(Scheduled<Void>)
|
||||
case unwrapped
|
||||
case closed
|
||||
}
|
||||
@@ -48,10 +48,12 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo
|
||||
private var shutdownPromise: EventLoopPromise<Void>?
|
||||
private var didDeliverData: Bool = false
|
||||
private var storedContext: ChannelHandlerContext? = nil
|
||||
private var shutdownTimeout: TimeAmount
|
||||
|
||||
internal init(connection: SSLConnection) {
|
||||
internal init(connection: SSLConnection, shutdownTimeout: TimeAmount) {
|
||||
self.connection = connection
|
||||
self.bufferedWrites = MarkedCircularBuffer(initialCapacity: 96) // 96 brings the total size of the buffer to just shy of one page
|
||||
self.shutdownTimeout = shutdownTimeout
|
||||
}
|
||||
|
||||
public func handlerAdded(context: ChannelHandlerContext) {
|
||||
@@ -174,7 +176,7 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo
|
||||
// We've been asked to close the connection, but we were currently unwrapping.
|
||||
// We don't have to send any CLOSE_NOTIFY, but we now need to upgrade ourselves:
|
||||
// closing is a more extreme activity than unwrapping.
|
||||
self.state = .closing
|
||||
self.state = .closing(self.scheduleTimedOutShutdown(context: context))
|
||||
if let promise = promise, let closePromise = self.closePromise {
|
||||
closePromise.futureResult.cascade(to: promise)
|
||||
} else if let promise = promise {
|
||||
@@ -190,7 +192,7 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo
|
||||
case .active, .handshaking:
|
||||
// We need to begin processing shutdown now. We can't fire the promise for a
|
||||
// while though.
|
||||
self.state = .closing
|
||||
self.state = .closing(self.scheduleTimedOutShutdown(context: context))
|
||||
closePromise = promise
|
||||
doShutdownStep(context: context)
|
||||
}
|
||||
@@ -254,15 +256,17 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo
|
||||
/// Once `state` has transitioned to `.closed`, further calls to this method will
|
||||
/// do nothing.
|
||||
private func doShutdownStep(context: ChannelHandlerContext) {
|
||||
guard self.state != .closed else {
|
||||
if case .closed = self.state {
|
||||
return
|
||||
}
|
||||
|
||||
let result = connection.doShutdown()
|
||||
|
||||
var uncleanScheduledShutdown: Scheduled<Void>?
|
||||
let targetCompleteState: ConnectionState
|
||||
switch self.state {
|
||||
case .closing:
|
||||
case .closing(let scheduledShutdown):
|
||||
uncleanScheduledShutdown = scheduledShutdown
|
||||
targetCompleteState = .closed
|
||||
case .unwrapping:
|
||||
targetCompleteState = .unwrapped
|
||||
@@ -274,7 +278,8 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo
|
||||
case .incomplete:
|
||||
writeDataToNetwork(context: context, promise: nil)
|
||||
case .complete:
|
||||
state = targetCompleteState
|
||||
uncleanScheduledShutdown?.cancel()
|
||||
self.state = targetCompleteState
|
||||
writeDataToNetwork(context: context, promise: nil)
|
||||
|
||||
// TODO(cory): This should probably fire out of the BoringSSL info callback.
|
||||
@@ -289,12 +294,22 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo
|
||||
preconditionFailure("Cannot be in \(targetCompleteState) at this code point")
|
||||
}
|
||||
case .failed(let err):
|
||||
uncleanScheduledShutdown?.cancel()
|
||||
// TODO(cory): This should probably fire out of the BoringSSL info callback.
|
||||
context.fireErrorCaught(NIOSSLError.shutdownFailed(err))
|
||||
channelClose(context: context, reason: NIOSSLError.shutdownFailed(err))
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a scheduled task to perform an unclean shutdown in event of a clean shutdown timing
|
||||
/// out. This task should be cancelled if the shutdown does not time out.
|
||||
private func scheduleTimedOutShutdown(context: ChannelHandlerContext) -> Scheduled<Void> {
|
||||
return context.eventLoop.scheduleTask(in: self.shutdownTimeout) {
|
||||
self.state = .closed
|
||||
self.channelClose(context: context, reason: NIOSSLCloseTimedOutError())
|
||||
}
|
||||
}
|
||||
|
||||
/// Loops over the `SSL` object, decoding encrypted application data until there is
|
||||
/// no more available.
|
||||
private func doDecodeData(context: ChannelHandlerContext) {
|
||||
@@ -334,7 +349,7 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo
|
||||
case .idle, .closed, .unwrapped, .handshaking:
|
||||
preconditionFailure("Should not get zeroReturn in \(self.state)")
|
||||
case .active:
|
||||
self.state = .closing
|
||||
self.state = .closing(self.scheduleTimedOutShutdown(context: context))
|
||||
case .unwrapping, .closing:
|
||||
break
|
||||
}
|
||||
|
||||
@@ -29,6 +29,6 @@ public final class NIOSSLServerHandler: NIOSSLHandler {
|
||||
connection.setVerificationCallback(verificationCallback)
|
||||
}
|
||||
|
||||
super.init(connection: connection)
|
||||
super.init(connection: connection, shutdownTimeout: context.configuration.shutdownTimeout)
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,9 @@ extension NIOSSLError: Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Closing the TLS channel cleanly timed out, so it was closed uncleanly.
|
||||
public struct NIOSSLCloseTimedOutError: Error {}
|
||||
|
||||
/// An enum that wraps individual BoringSSL errors directly.
|
||||
public enum BoringSSLError: Error {
|
||||
case noError
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import CNIOBoringSSL
|
||||
import NIO
|
||||
|
||||
/// Known and supported TLS versions.
|
||||
public enum TLSVersion {
|
||||
@@ -145,9 +146,13 @@ public struct TLSConfiguration {
|
||||
self.encodedApplicationProtocols = newValue.map(encodeALPNIdentifier)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
internal var encodedApplicationProtocols: [[UInt8]]
|
||||
|
||||
/// The amount of time to wait after initiating a shutdown before performing an unclean
|
||||
/// shutdown. Defaults to 5 seconds.
|
||||
public var shutdownTimeout: TimeAmount
|
||||
|
||||
/// A callback that can be used to implement `SSLKEYLOGFILE` support.
|
||||
public var keyLogCallback: NIOSSLKeyLogCallback?
|
||||
|
||||
@@ -159,6 +164,7 @@ public struct TLSConfiguration {
|
||||
certificateChain: [NIOSSLCertificateSource],
|
||||
privateKey: NIOSSLPrivateKeySource?,
|
||||
applicationProtocols: [String],
|
||||
shutdownTimeout: TimeAmount,
|
||||
keyLogCallback: NIOSSLKeyLogCallback?) {
|
||||
self.cipherSuites = cipherSuites
|
||||
self.minimumTLSVersion = minimumTLSVersion
|
||||
@@ -168,6 +174,7 @@ public struct TLSConfiguration {
|
||||
self.certificateChain = certificateChain
|
||||
self.privateKey = privateKey
|
||||
self.encodedApplicationProtocols = []
|
||||
self.shutdownTimeout = shutdownTimeout
|
||||
self.applicationProtocols = applicationProtocols
|
||||
self.keyLogCallback = keyLogCallback
|
||||
}
|
||||
@@ -184,6 +191,7 @@ public struct TLSConfiguration {
|
||||
certificateVerification: CertificateVerification = .none,
|
||||
trustRoots: NIOSSLTrustRoots = .default,
|
||||
applicationProtocols: [String] = [],
|
||||
shutdownTimeout: TimeAmount = .seconds(5),
|
||||
keyLogCallback: NIOSSLKeyLogCallback? = nil) -> TLSConfiguration {
|
||||
return TLSConfiguration(cipherSuites: cipherSuites,
|
||||
minimumTLSVersion: minimumTLSVersion,
|
||||
@@ -193,6 +201,7 @@ public struct TLSConfiguration {
|
||||
certificateChain: certificateChain,
|
||||
privateKey: privateKey,
|
||||
applicationProtocols: applicationProtocols,
|
||||
shutdownTimeout: shutdownTimeout,
|
||||
keyLogCallback: keyLogCallback)
|
||||
}
|
||||
|
||||
@@ -209,6 +218,7 @@ public struct TLSConfiguration {
|
||||
certificateChain: [NIOSSLCertificateSource] = [],
|
||||
privateKey: NIOSSLPrivateKeySource? = nil,
|
||||
applicationProtocols: [String] = [],
|
||||
shutdownTimeout: TimeAmount = .seconds(5),
|
||||
keyLogCallback: NIOSSLKeyLogCallback? = nil) -> TLSConfiguration {
|
||||
return TLSConfiguration(cipherSuites: cipherSuites,
|
||||
minimumTLSVersion: minimumTLSVersion,
|
||||
@@ -218,6 +228,7 @@ public struct TLSConfiguration {
|
||||
certificateChain: certificateChain,
|
||||
privateKey: privateKey,
|
||||
applicationProtocols: applicationProtocols,
|
||||
shutdownTimeout: shutdownTimeout,
|
||||
keyLogCallback: keyLogCallback)
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ extension NIOSSLIntegrationTest {
|
||||
("testForcingVerificationFailure", testForcingVerificationFailure),
|
||||
("testExtractingCertificates", testExtractingCertificates),
|
||||
("testRepeatedClosure", testRepeatedClosure),
|
||||
("testClosureTimeout", testClosureTimeout),
|
||||
("testReceivingGibberishAfterAttemptingToClose", testReceivingGibberishAfterAttemptingToClose),
|
||||
("testPendingWritesFailWhenFlushedOnClose", testPendingWritesFailWhenFlushedOnClose),
|
||||
("testChannelInactiveAfterCloseNotify", testChannelInactiveAfterCloseNotify),
|
||||
|
||||
@@ -1285,6 +1285,55 @@ class NIOSSLIntegrationTest: XCTestCase {
|
||||
XCTAssertTrue(closed)
|
||||
}
|
||||
|
||||
func testClosureTimeout() throws {
|
||||
let serverChannel = EmbeddedChannel()
|
||||
let clientChannel = EmbeddedChannel()
|
||||
|
||||
defer {
|
||||
// We expect both cases to throw
|
||||
XCTAssertThrowsError(try serverChannel.finish())
|
||||
XCTAssertThrowsError(try clientChannel.finish())
|
||||
}
|
||||
|
||||
let context = try assertNoThrowWithValue(configuredSSLContext())
|
||||
|
||||
XCTAssertNoThrow(try serverChannel.pipeline.addHandler(NIOSSLServerHandler(context: context)).wait())
|
||||
XCTAssertNoThrow(try clientChannel.pipeline.addHandler(NIOSSLClientHandler(context: context, serverHostname: nil)).wait())
|
||||
let handshakeHandler = HandshakeCompletedHandler()
|
||||
XCTAssertNoThrow(try clientChannel.pipeline.addHandler(handshakeHandler).wait())
|
||||
|
||||
// Connect. This should lead to a completed handshake.
|
||||
let addr: SocketAddress = try SocketAddress(unixDomainSocketPath: "/tmp/whatever")
|
||||
let connectFuture = clientChannel.connect(to: addr)
|
||||
serverChannel.pipeline.fireChannelActive()
|
||||
try interactInMemory(clientChannel: clientChannel, serverChannel: serverChannel)
|
||||
try connectFuture.wait()
|
||||
XCTAssertTrue(handshakeHandler.handshakeSucceeded)
|
||||
|
||||
var closed = false
|
||||
clientChannel.close().whenComplete { _ in
|
||||
closed = true
|
||||
}
|
||||
|
||||
clientChannel.close().whenFailure { error in
|
||||
XCTAssertTrue(error is NIOSSLCloseTimedOutError)
|
||||
}
|
||||
|
||||
// Send CLOSE_NOTIFY from the client.
|
||||
while let clientDatum = try clientChannel.readOutbound(as: IOData.self) {
|
||||
try serverChannel.writeInbound(clientDatum)
|
||||
}
|
||||
|
||||
XCTAssertFalse(closed)
|
||||
|
||||
// Let the shutdown timeout.
|
||||
clientChannel.embeddedEventLoop.advanceTime(by: context.configuration.shutdownTimeout)
|
||||
XCTAssertTrue(closed)
|
||||
|
||||
// Let the server shutdown.
|
||||
try interactInMemory(clientChannel: clientChannel, serverChannel: serverChannel)
|
||||
}
|
||||
|
||||
func testReceivingGibberishAfterAttemptingToClose() throws {
|
||||
let serverChannel = EmbeddedChannel()
|
||||
let clientChannel = EmbeddedChannel()
|
||||
|
||||
Reference in new issue
Block a user