mirror of
https://github.com/apple/swift-nio-ssl
synced 2026-11-22 04:30:44 +00:00
Don't crash when a peer completes an optionalVerification handshake without a certificate (#590)
## Motivation When a `NIOSSLHandler` is created with an `additionalPeerCertificateVerificationCallback` (via `_makeSSLServerHandler` / `_makeSSLClientHandler`) and the `TLSConfiguration` uses `.optionalVerification`, the peer is allowed to complete the handshake *without* presenting a certificate. In that situation `doHandshakeStep` reached the additional-verification branch, called `connection.getPeerCertificate()`, got `nil`, and hit a `preconditionFailure`, aborting the entire process. The constructor precondition did not catch this because `.optionalVerification` is `.none(validatePresentedCertificates: true)`, which is distinct from `.none` and therefore passes the `!= .none` check. ## Modifications - In `NIOSSLHandler.doHandshakeStep`, only invoke the `additionalPeerCertificateVerificationCallback` when the peer actually presented a certificate. The callback binding and the `getPeerCertificate()` binding are now combined into a single `if let ..., let ...`; if no certificate was presented the handshake completes normally without invoking the callback. This preserves the previous behaviour of only calling `getPeerCertificate()` when a callback is set (short-circuit ordering). - Removed the now-unreachable `preconditionFailure`. - Added an integration test that stands up a server with `.optionalVerification` and an `additionalPeerCertificateVerificationCallback`, connects a client that presents no certificate, and asserts the connection is handled without crashing the process. ## Result A peer that completes an `.optionalVerification` handshake without presenting a certificate no longer crashes the process. The additional verification callback still runs, unchanged, whenever a certificate *is* presented, so behaviour for the certificate-present path is unaffected. `.optionalVerification` + `additionalPeerCertificateVerificationCallback` is now a genuinely supported combination, matching what the constructor precondition already advertised. --------- Co-authored-by: Aryan Shah <aryan_shah@apple.com>
This commit is contained in:
1 parent
9a03669fe5
commit
8d8f7844d7
4 files changed
+174
-15
No files matched your search
@@ -1,5 +1,6 @@
|
||||
.DS_Store
|
||||
/.build
|
||||
*/.build
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
Package.pins
|
||||
@@ -9,3 +10,4 @@ Package.resolved
|
||||
DerivedData
|
||||
/.idea
|
||||
.swiftpm
|
||||
.vscode
|
||||
@@ -376,23 +376,32 @@ public class NIOSSLHandler: ChannelInboundHandler, ChannelOutboundHandler, Remov
|
||||
}
|
||||
|
||||
if let additionalPeerCertificateVerificationCallback = self.additionalPeerCertificateVerificationCallback {
|
||||
state = .additionalVerification
|
||||
guard let peerCertificate = connection.getPeerCertificate() else {
|
||||
preconditionFailure(
|
||||
"""
|
||||
Couldn't get peer certificate after chain verification was successful.
|
||||
This should be impossible as we have a precondition during creation of this handler that requires certificate verification.
|
||||
Please file an issue.
|
||||
"""
|
||||
if let peerCertificate = connection.getPeerCertificate() {
|
||||
state = .additionalVerification
|
||||
additionalPeerCertificateVerificationCallback(peerCertificate, context.channel)
|
||||
.hop(to: context.eventLoop)
|
||||
.assumeIsolated()
|
||||
.whenComplete { result in
|
||||
self.completedAdditionalPeerCertificateVerification(result: result)
|
||||
}
|
||||
return
|
||||
} else if self.connection.parentContext.configuration.certificateVerification.requiresPeerCertificate {
|
||||
// The peer presented no certificate even though verification required one.
|
||||
// BoringSSL sets `SSL_VERIFY_FAIL_IF_NO_PEER_CERT` for these modes, so it
|
||||
// should have failed the handshake before reaching `.complete`; this branch
|
||||
// should be unreachable. If it ever is reached we must fail closed rather
|
||||
// than accept an unauthenticated peer or silently skip the callback.
|
||||
assertionFailure(
|
||||
"Reached handshake completion with no peer certificate despite required certificate verification."
|
||||
)
|
||||
let error = NIOSSLError.noCertificateToValidate
|
||||
context.fireErrorCaught(error)
|
||||
channelClose(context: context, reason: error)
|
||||
return
|
||||
}
|
||||
additionalPeerCertificateVerificationCallback(peerCertificate, context.channel)
|
||||
.hop(to: context.eventLoop)
|
||||
.assumeIsolated()
|
||||
.whenComplete { result in
|
||||
self.completedAdditionalPeerCertificateVerification(result: result)
|
||||
}
|
||||
return
|
||||
// Otherwise verification is optional and the peer presented no certificate: there
|
||||
// is nothing to verify, so we skip the callback and accept the connection,
|
||||
// consistent with `.optionalVerification`'s semantics.
|
||||
}
|
||||
|
||||
state = .active
|
||||
|
||||
@@ -212,6 +212,21 @@ extension CertificateVerification: Hashable {
|
||||
// empty
|
||||
}
|
||||
|
||||
extension CertificateVerification {
|
||||
/// Whether this mode requires the peer to present a certificate.
|
||||
///
|
||||
/// This must stay in sync with the BoringSSL verification setup in `NIOSSLContext`: only the
|
||||
/// modes that map to `SSL_VERIFY_FAIL_IF_NO_PEER_CERT` require a certificate.
|
||||
internal var requiresPeerCertificate: Bool {
|
||||
switch self {
|
||||
case .fullVerification, .noHostnameVerification:
|
||||
return true
|
||||
case .none:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for TLS renegotiation.
|
||||
///
|
||||
/// In general, renegotiation should not be enabled except in circumstances where it is absolutely necessary.
|
||||
|
||||
@@ -1521,6 +1521,139 @@ class NIOSSLIntegrationTest: XCTestCase {
|
||||
XCTAssertTrue(actualErrors.first is CustomUserError)
|
||||
}
|
||||
|
||||
func testOptionalVerificationWithAdditionalCallbackAndNoClientCertificateDoesNotCrash() throws {
|
||||
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||
defer {
|
||||
XCTAssertNoThrow(try group.syncShutdownGracefully())
|
||||
}
|
||||
|
||||
// Server: `.optionalVerification` (requests but does not require a client cert) plus
|
||||
// an additional peer-certificate verification callback.
|
||||
var serverConfig = TLSConfiguration.makeServerConfiguration(
|
||||
certificateChain: [.certificate(NIOSSLIntegrationTest.cert)],
|
||||
privateKey: .privateKey(NIOSSLIntegrationTest.key)
|
||||
)
|
||||
serverConfig.certificateVerification = .optionalVerification
|
||||
serverConfig.trustRoots = .certificates([NIOSSLIntegrationTest.cert])
|
||||
let serverCtx = try assertNoThrowWithValue(NIOSSLContext(configuration: serverConfig))
|
||||
|
||||
// Client presents no certificate of its own.
|
||||
let clientCtx = try configuredClientContext()
|
||||
|
||||
let serverChannel = try assertNoThrowWithValue(
|
||||
ServerBootstrap(group: group)
|
||||
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
|
||||
.childChannelInitializer { channel in
|
||||
channel.eventLoop.makeCompletedFuture {
|
||||
let handler = NIOSSLServerHandler._makeSSLServerHandler(
|
||||
context: serverCtx,
|
||||
additionalPeerCertificateVerificationCallback: { _, channel in
|
||||
channel.eventLoop.makeSucceededFuture(())
|
||||
}
|
||||
)
|
||||
try channel.pipeline.syncOperations.addHandler(handler)
|
||||
}
|
||||
}
|
||||
.bind(host: "127.0.0.1", port: 0).wait()
|
||||
)
|
||||
defer {
|
||||
XCTAssertNoThrow(try serverChannel.close().wait())
|
||||
}
|
||||
|
||||
let eventHandler = EventRecorderHandler<TLSUserEvent>()
|
||||
let clientChannel = try clientTLSChannel(
|
||||
context: clientCtx,
|
||||
preHandlers: [],
|
||||
postHandlers: [eventHandler],
|
||||
group: group,
|
||||
connectingTo: serverChannel.localAddress!,
|
||||
serverHostname: "localhost"
|
||||
)
|
||||
defer {
|
||||
XCTAssertNoThrow(try? clientChannel.close().wait())
|
||||
}
|
||||
|
||||
var originalBuffer = clientChannel.allocator.buffer(capacity: 5)
|
||||
originalBuffer.writeString("Hello")
|
||||
let writeFuture = clientChannel.writeAndFlush(originalBuffer)
|
||||
writeFuture.whenComplete { _ in
|
||||
XCTAssertEqual(
|
||||
eventHandler.events[..<3],
|
||||
[.Registered, .Active, .UserEvent(.handshakeCompleted(negotiatedProtocol: nil))]
|
||||
)
|
||||
}
|
||||
try writeFuture.wait()
|
||||
}
|
||||
|
||||
// A server that *requires* a client certificate (`.fullVerification`) and has an additional
|
||||
// peer certificate verification callback must reject a client that presents no certificate,
|
||||
// and must never invoke the callback for such a connection. BoringSSL enforces this with
|
||||
// `SSL_VERIFY_FAIL_IF_NO_PEER_CERT` before the handshake completes; this test guards against a
|
||||
// regression that would fail open (accept the connection and/or skip the callback) instead.
|
||||
func testFullVerificationWithAdditionalCallbackRejectsClientWithNoCertificate() throws {
|
||||
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||
defer {
|
||||
XCTAssertNoThrow(try group.syncShutdownGracefully())
|
||||
}
|
||||
|
||||
// Server: `.fullVerification` (requires a client cert) plus an additional
|
||||
// peer-certificate verification callback.
|
||||
var serverConfig = TLSConfiguration.makeServerConfiguration(
|
||||
certificateChain: [.certificate(NIOSSLIntegrationTest.cert)],
|
||||
privateKey: .privateKey(NIOSSLIntegrationTest.key)
|
||||
)
|
||||
serverConfig.certificateVerification = .fullVerification
|
||||
serverConfig.trustRoots = .certificates([NIOSSLIntegrationTest.cert])
|
||||
let serverCtx = try assertNoThrowWithValue(NIOSSLContext(configuration: serverConfig))
|
||||
|
||||
// Client presents no certificate of its own.
|
||||
let clientCtx = try configuredClientContext()
|
||||
|
||||
let callbackInvoked = NIOLockedValueBox(false)
|
||||
let errorHandler = ErrorCatcher<Error>()
|
||||
|
||||
let serverChannel = try assertNoThrowWithValue(
|
||||
ServerBootstrap(group: group)
|
||||
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
|
||||
.childChannelInitializer { channel in
|
||||
channel.eventLoop.makeCompletedFuture {
|
||||
let handler = NIOSSLServerHandler._makeSSLServerHandler(
|
||||
context: serverCtx,
|
||||
additionalPeerCertificateVerificationCallback: { _, channel in
|
||||
callbackInvoked.withLockedValue { $0 = true }
|
||||
return channel.eventLoop.makeSucceededFuture(())
|
||||
}
|
||||
)
|
||||
try channel.pipeline.syncOperations.addHandler(handler)
|
||||
}
|
||||
}
|
||||
.bind(host: "127.0.0.1", port: 0).wait()
|
||||
)
|
||||
defer {
|
||||
XCTAssertNoThrow(try serverChannel.close().wait())
|
||||
}
|
||||
|
||||
let clientChannel = try clientTLSChannel(
|
||||
context: clientCtx,
|
||||
preHandlers: [],
|
||||
postHandlers: [errorHandler],
|
||||
group: group,
|
||||
connectingTo: serverChannel.localAddress!,
|
||||
serverHostname: "localhost"
|
||||
)
|
||||
defer {
|
||||
XCTAssertNoThrow(try? clientChannel.close().wait())
|
||||
}
|
||||
|
||||
// Wait for the connection to be torn down as a result of the failed handshake.
|
||||
try clientChannel.closeFuture.wait()
|
||||
|
||||
// The handshake must have failed on the client, and the server's additional verification
|
||||
// callback must never run when no certificate was presented.
|
||||
XCTAssertFalse(errorHandler.errors.isEmpty)
|
||||
XCTAssertFalse(callbackInvoked.withLockedValue { $0 })
|
||||
}
|
||||
|
||||
func testFlushWhileAdditionalValidationIsInProgressDoesNotActuallyFlush() throws {
|
||||
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||
defer {
|
||||
|
||||
Reference in new issue
Block a user